Drive.Permissions.insert(值)-Drive API,您可以在“值”下使用数组吗?

use*_*276 3 google-apps-script google-drive-api

是否可以在此处使用“值”下的数组来阻止我创建组别名电子邮件地址?例如:

userValues = ["user1@abc.com", "user2@abc.com", "user3@abc.com"];

Drive.Permissions.insert({
    'role': 'writer',
    'type': 'user',
    'value': ** userValues ** ,
  },
  folder, {
    'sendNotificationEmails': 'false'
  });
Run Code Online (Sandbox Code Playgroud)

Tan*_*ike 5

这是我的理解:

  • 您想要使用多个电子邮件地址授予文件和文件夹权限。
    • 例如,您想使用类似的数组userValues = ["user1@abc.com", "user2"@abc.com", "user3@abc.com"];
  • 您希望使用 Google Apps 脚本来实现此目的。

问题和解决方法:

现阶段Drive.Permissions.insert()可以为一封邮件创建权限。不幸的是,无法通过一次调用使用多个电子邮件来创建权限Drive.Permissions.insert()。如果要Drive.Permissions.insert在当前阶段使用数组 和 ,则需要Drive.Permissions.insert在 for 循环中运行。

作为解决方法,在这里,我想建议使用批量请求。使用批量请求时,一次API调用可以完成100个API调用,并且可以与异步进程一起运行。

模式一:

在此模式中,批处理请求使用 UrlFetchApp 运行。

示例脚本:

在运行脚本之前,请设置文件 ID 和电子邮件地址。如果要给文件夹添加权限,请将文件夹ID设置为###of const fileId = "###";

function myFunction() {
  const fileId = "###";  // Please set the file ID.
  const userValues = ["user1@abc.com", "user2"@abc.com", "user3@abc.com"];  // Please set the email addresses.
  
  const resources = userValues.map(e => ({role: "writer", type: "user", emailAddress: e}));
  const boundary = "xxxxxxxxxx";
  const payload = resources.reduce((s, e, i) => {
    s += "Content-Type: application/http\r\n" +
      "Content-ID: " + i + "\r\n\r\n" +
      "POST https://www.googleapis.com/drive/v3/files/" + fileId + "/permissions?sendNotificationEmails=false" + "\r\n" +
      "Content-Type: application/json; charset=utf-8\r\n\r\n" +
      JSON.stringify(e) + "\r\n" +
      "--" + boundary + "\r\n";
    return s;
  }, "--" + boundary + "\r\n");
  const params = {
    method: "post",
    contentType: "multipart/mixed; boundary=" + boundary,
    payload: payload,
    headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
  };
  const res = UrlFetchApp.fetch("https://www.googleapis.com/batch", params);
  console.log(res.getContentText())
}
Run Code Online (Sandbox Code Playgroud)

模式2:

在此模式中,使用用于批量请求的 Google Apps 脚本库。

示例脚本:

在运行脚本之前,请设置文件ID和电子邮件地址,并安装GAS库。

function myFunction() {
  const fileId = "###";  // Please set the file ID.
  const userValues = ["user1@abc.com", "user2"@abc.com", "user3@abc.com"];  // Please set the email addresses.
  
  const reqs = userValues.map(e => ({
    method: "POST",
    endpoint: "https://www.googleapis.com/drive/v3/files/" + fileId + "/permissions?sendNotificationEmails=false",
    requestBody: {role: "writer", type: "user", emailAddress: e},
  }));
  const requests = {batchPath: "batch/drive/v3", requests: reqs};
  const res = BatchRequest.Do(requests);
  console.log(res.getContentText())
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 请在脚本编辑器中启用 V8。
  • 在上面的脚本中,作为示例脚本,最大请求数为100。如果您想请求超过100,请修改上面的脚本。请小心这一点。

参考: