如何通过Google Script API (Node.js)添加库?



我正在开发一个应用程序,可以自动创建具有容器绑定脚本的谷歌电子表格。为了使脚本的维护更容易,脚本没有业务逻辑,而是有委托代码,如下所示。

container-bound script
const onOpen = (e) => {
lib.onOpen(e)
}

要做到这一点,我要"add libraries"对容器绑定脚本项目具有实际的业务逻辑。我知道如何手动实现,但我也想使用谷歌脚本API SDK为Node.js自动化它。我试图找到一种方法,但似乎SDK不支持以编程方式向脚本项目添加库。

有人有解决办法吗?

谢谢,

在这种情况下,我认为您可以通过修改清单文件(appsscript.json)来添加库。安装库的示例appsscript.json如下所示。并且,Google Apps Script API可以编辑appsscript.json

样品appsscript.json:

{
"timeZone": "Asia/Tokyo",
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"dependencies": {
"libraries": [ // <--- Here, you can install the library.
{
"userSymbol": "lib",
"version": "0",
"libraryId": "### ID of library ###",
"developmentMode": true
}
]
}
}

示例脚本:

当上面的解释反映在Node.js的样例脚本中时,它变成如下所示。在本例中,使用了Node.js的googleapi。

const scriptId = "###"; // Please set the script ID of the Google Apps Script project.
const lib = {
userSymbol: "lib",
version: "0",
libraryId: "### ID of library ###",
developmentMode: true,
};
const script = google.script({ version: "v1", auth }); // Please use your "auth" in your script.
// 1. Retrieve the existing scripts from Google Apps Script project.
const res1 = await script.projects.getContent({ scriptId: scriptId }).catch((err) => console.log(err.errors));
if (!res1) return;
// 2. Modify `appsscript.json` file.
const files = res1.data.files.map((e) => {
if (e.name == "appsscript") {
const obj = JSON.parse(e.source);
if (
obj.dependencies.libraries &&
!obj.dependencies.libraries.some(
({ libraryId }) => libraryId == lib.libraryId
)
) {
obj.dependencies.libraries.push(lib);
} else {
obj.dependencies.libraries = [lib];
}
e.source = JSON.stringify(obj, null, "  ");
}
return e;
});
// 3. Update Google Apps Script project with the modified `appsscript.json` file.
const res2 = await script.projects
.updateContent({ scriptId: scriptId, resource: { files: files } })
.catch((err) => console.log(err.errors));
if (!res2) return;
console.log("Done.");

注意:

  • 在这个答案中,它假设你已经能够使用Node.js的Google Apps Script API获取和放置Google Apps Script项目的值。请小心。

引用:

  • <
  • 清单结构/gh>
  • google-api-nodejs-client

最新更新