- An XML file that contains the code below is available to download
- box-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(){
const newFolderName = configs.get("FolderName");
checkNewFolderName(newFolderName);
const parentFolderId = configs.get("ParentFolderId");
// get OAuth2 Setting
const oauth2 = configs.get("conf_OAuth2");
const newFolderId = createFolder(oauth2, parentFolderId, newFolderName);
const IdData = configs.get("FolderIdItem");
const UrlData = configs.get("WebViewUrlItem");
if (IdData !== null && IdData !== "") {
engine.setDataByNumber(IdData, newFolderId);
}
if (UrlData !== null && UrlData !== "") {
engine.setDataByNumber(UrlData, `https://app.box.com/folder/${newFolderId}`);
}
}
/**
* 新しいフォルダのフォルダ名をチェックする。(サポートされていない文字が使われていないか)
*/
function checkNewFolderName(newFolderName){
//空ではないか
if(newFolderName === "" ||newFolderName === null) {
throw "Folder Name is blank";
}
//255文字を超えていないか
if(newFolderName.length > 255){
throw"Folder Name shoule be less than 256 characters";
}
//「/」や「\」が含まれていないか
const reg = new RegExp('[/\\\\]');
if(newFolderName.search(reg) !== -1) {
throw "Invalid Folder Name";
}
//先頭と末尾に半角スペースが使われていないか
if(newFolderName.slice(0,1) === " " || newFolderName.slice(-1) === " ") {
throw "Invalid Folder Name";
}
//「.」や「..」ではないか
if(newFolderName === "." || newFolderName === ".."){
throw "Invalid Folder Name";
}
}
//create folder on box
function createFolder(oauth2, parentFolderId, name) {
let jsonReq = {};
//mime type of google drive folder
if (parentFolderId !== "" && parentFolderId !== null){
jsonReq["parent"] = {"id": parentFolderId };
}else{
jsonReq["parent"]= {"id": 0 };
}
jsonReq["name"] = name;
const url = 'https://api.box.com/2.0/folders';
const response = httpClient.begin()
.authSetting(oauth2)
.queryParam("fields", "id")
.body(JSON.stringify(jsonReq), "application/json; charset=UTF-8")
.post(url);
const status = response.getStatusCode();
const responseTxt = response.getResponseAsString();
let jsonRes;
try {
jsonRes = JSON.parse(responseTxt);
} catch(e) {
engine.log("failed to parse as json");
engine.log(responseTxt);
throw `Failed to create. status: ${status}`;
}
// フォルダ作成成功
if (status === 201) {
return jsonRes.id;
}
try {
if(status === 409 && jsonRes.context_info.conflicts[0].type === "folder"){
// 既存のフォルダと Conflict した場合は、既存 フォルダの ID を返す
return jsonRes.context_info.conflicts[0].id;
}
} catch (e) {
// 何もしない(上記のケース以外はすべてエラーにする)
}
engine.log(responseTxt);
throw `Failed to create. status: ${status}`;
}
Pingback: Utilising Box From Your Workflow – Questetra Support