我想知道如何在Google Apps脚本中使用UrlFetchApp制作Drive API批量请求。我已经阅读了谷歌文档,但我仍然不清楚。我想将下面的代码转换为接受多个文件ID的批处理请求。
"scripts": {
"build": "NODE_ENV=production next build",
},
我尝试使用var url = 'https://www.googleapis.com/drive/v2/files/FILEID/permissions';
var data = {
"role":"owner",
"type":"user",
"value": NEWOWNER
};
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + AUTHORIZATIONTOKEN
},
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(data),
});
var result = JSON.parse(response.getContentText());
,但似乎无效。我刚看到将每个文件请求嵌套到批处理请求的描述,但到目前为止我还没有找到正确执行它的语法示例。
一些见解会有所帮助。谢谢!
答案 0 :(得分:1)
这个示例脚本怎么样?当我看到this document时,我发现您要使用multipart/mixed
发送要进行批量请求的API调用。通过这种方式,我可以为Google Apps脚本创建示例脚本,如下所示。
function myFunction() {
var body = [
{
method: "POST",
endpoint: "https://www.googleapis.com/drive/v3/files/### fileId 1 ###/permissions",
requestBody: {
"role": "owner",
"type": "user",
"emailAddress": NEWOWNER
}
},
{
method: "POST",
endpoint: "https://www.googleapis.com/drive/v3/files/### fileId 2 ###/permissions",
requestBody: {
"role": "owner",
"type": "user",
"emailAddress": NEWOWNER
}
}
];
var boundary = "xxxxxxxxxx";
var contentId = 0;
var data = "--" + boundary + "\r\n";
for (var i in body) {
data += "Content-Type: application/http\r\n";
data += "Content-ID: " + ++contentId + "\r\n\r\n";
data += body[i].method + " " + body[i].endpoint + "\r\n";
data += body[i].requestBody ? "Content-Type: application/json; charset=utf-8\r\n\r\n" : "\r\n";
data += body[i].requestBody ? JSON.stringify(body[i].requestBody) + "\r\n" : "";
data += "--" + boundary + "\r\n";
}
var payload = Utilities.newBlob(data).getBytes();
var options = {
method: "post",
contentType: "multipart/mixed; boundary=" + boundary,
payload: payload,
headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
muteHttpExceptions: true,
};
var res = UrlFetchApp.fetch("https://www.googleapis.com/batch", options).getContentText();
Logger.log(res);
}
在我的环境中,我确认这是有效的。但如果这在您的环境中无效,请告诉我。我想修改。