- An XML file that contains the code below is available to download
- google-drive-folder-create.xml (C) Questetra, Inc. (MIT License)
- If you are using Professional, you can modify the contents of this file and use it as your own add-on
main();
function main() {
let parentFolderId = configs.get("ParentFolderId");
const folderName = configs.get("FolderName");
if (folderName === "" || folderName === null) {
throw "Folder Name is blank";
}
const quser = configs.getObject("UserID");
checkUser(quser);
const json = createFolder(quser, parentFolderId, folderName);
setData("FolderIdItem", json, "id");
setData("WebViewUrlItem", json, "webViewLink");
}
/**
* ユーザーIDをチェックする
* @param {QuserView} quser ユーザ
*/
function checkUser(quser) {
if (quser === null) {
throw "User not found";
}
}
/**
* プロセスにデータを保存する
* @param {String} configName 保存先データ項目の config 名
* @param {Object} json 保存するデータをメンバに持つ JSON オブジェクト
* @param {String} property 保存するデータのプロパティ名
*/
function setData(configName, json, property) {
const item = configs.get(configName);
if (item === null || item === "") {
return;
}
const data = json[property];
engine.setDataByNumber(item, data);
}
/**
* Google ドライブにフォルダを作成する
* @param {QuserView} quser ユーザ
* @param {String} parentFolderId 親フォルダのID
* @param {String} name フォルダ名
* @return {Object} jsonRes レスポンス本文の JSON オブジェクト
*/
function createFolder(quser, parentFolderId, name) {
let reqBody = {};
//mime type of google drive folder
reqBody["mimeType"] = "application/vnd.google-apps.folder";
if (parentFolderId !== "" && parentFolderId !== null) {
reqBody["parents"] = [parentFolderId];
}
reqBody["name"] = name;
const url = "https://www.googleapis.com/drive/v3/files/";
const response = httpClient
.begin()
.googleOAuth2(quser, "Drive")
.queryParam("fields", "id, webViewLink")
.queryParam("supportsAllDrives", "true")
.body(JSON.stringify(reqBody), "application/json; charset=UTF-8")
.post(url);
const status = response.getStatusCode();
const responseTxt = response.getResponseAsString();
if (status >= 300) {
const error = `Failed to create\nstatus:${status}`;
engine.log(responseTxt);
throw error;
}
engine.log(`status:${status}`);
const jsonRes = JSON.parse(responseTxt);
return jsonRes;
}