I m developing an app that automates creating google spreadsheets that have a container-bound script. To make the maintenance of the script easy, the script doesn't have business logic but have delegation codes instead as below.
container-bound script
const onOpen = (e) => {
lib.onOpen(e)
}
To do so, I wanna "add libraries" that have actual business logic to the container-bound script project. I know how to achieve that manually but I also wanna automate it using Google Script API SDK for Node.js. I tried to find a way but seems the SDK doesn't support to add libraries to script project programmatically.
Do anybody have a solution for it ?
Thanks,
CodePudding user response:
In that case, I thought that you can add the library by modifying the manifest file (appsscript.json
). The sample appsscript.json
for installing the library is as follows. And, Google Apps Script API can edit appsscript.json
.
Sample 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
}
]
}
}
Sample script:
When the above explanation is reflected in the sample script for Node.js, it becomes as follows. In this case, googleapis for Node.js is used.
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.");
Note:
- In this answer, it supposes that you have already been able to get and put values for Google Apps Script project using Google Apps Script API with Node.js. Please be careful about this.