在1个URLFetchApp调用中将几个成员添加到Google网上论坛?

时间:2019-07-31 19:38:20

标签: google-apps-script urlfetch google-groups-api

是否可以使用1个URLFetchApp.fetch调用将少量成员添加到Google网上论坛?尝试减少我的应用程序中的提取调用次数。

我可以为每个成员拨打1个电话,将其添加到Google网上论坛。

var obj = JSON.parse(jsonStr);
    for(var h=1; h< mailingData.length;h++) {
        obj["members"].push({"email":mailingData[h][column],"role":"MEMBER"});
    }
    jsonStr = JSON.stringify(obj);
    Logger.log(jsonStr);
    fetchArgs.method = "POST";
    fetchArgs.contentType = "application/json";
    fetchArgs.headers = {Authorization: 'Bearer ' + myService.getAccessToken()};
    fetchArgs.muteHttpExceptions=true;
    fetchArgs.payload = jsonStr;
    var url = 'https://www.googleapis.com/admin/directory/v1/groups/'+group+'/members';
    var res = UrlFetchApp.fetch(url, fetchArgs);

这是jsonStr的打印输出:

{"members":[
{"email":"devon@myorg.com","role":"MEMBER"}, 
{"email":"jake_smith@myorg.com","role":"MEMBER"}, 
{"email":"robert_keys@myorg.com","role":"MEMBER"}
]}

The error I get when I print the response is the following: 
[19-07-31 16:21:18:451 EDT] {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Missing required field: member"
   }
  ],
   "code": 400,
   "message": "Missing required field: member"
 }
}

1 个答案:

答案 0 :(得分:1)

在App Script中,您可以使用fetchAll()函数发出批处理请求[1]。我在您的代码中实现了fetchAll,创建了一个空的请求数组,并为每个用户的每个请求填充了它。假设您从mailingData数组中收到一封电子邮件,一个正确的授权令牌以及url中已经存在一个组电子邮件(我对这些更改进行了测试),以下代码将起作用:

  var requests = []

  for(var h=1; h< mailingData.length; h++) {

  var data = {"email":mailingData[h][column], "role":"MEMBER"};
  var jsonStr = JSON.stringify(data);
  var request = {};

  request.url = 'https://www.googleapis.com/admin/directory/v1/groups/'+group+'/members'; 
  request.method = "POST";
  request.contentType = "application/json";
  request.headers = {Authorization: 'Bearer ' + myService.getAccessToken()}; 
  request.muteHttpExceptions=true;
  request.payload = jsonStr;

  requests.push(request);
  }

  var response = UrlFetchApp.fetchAll(requests);

[1] https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetchAll(Object)