Box: Create Folder
Create a new folder in the specified folder on Box, and save the folder ID and URL. When there is the folder having the same name, save that folder ID and URL.
2020-07-27 (C) Questetra, Inc. (MIT License)
Configs
  • C1: OAuth2 Setting Name *
  • C2: Parent Folder ID (Root Folder if blank) #{EL}
  • C3: Folder Name to create * #{EL}
  • C4: String type data Item that will save Folder ID
  • C5: String type data Item that will save Folder URL
Script
main();
function main(){
  const newFolderName = configs.get("FolderName");
  checkNewFolderName(newFolderName);

  const parentFolderId = configs.get("ParentFolderId");
  
  // get OAuth token
  const token = httpClient.getOAuth2Token(configs.get("conf_OAuth2"));

  const newFolderId = createFolder(token, 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(token, 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()
    .bearer(token)
    .body(JSON.stringify(jsonReq), "application/json; charset=UTF-8")
    .post(url);
  const status = response.getStatusCode();
  const responseTxt = response.getResponseAsString();

  engine.log(`status: ${status}`);
  engine.log(responseTxt);

  let jsonRes;
   try {
     jsonRes = JSON.parse(responseTxt);
   } catch(e) {
     engine.log("failed to parse as json");
     throw `Failed to creat. status: ${status}`;
   }

  


  try{
    if (status === 409){
      if(jsonRes["context_info"]["conflicts"][0]["type"] === "folder"){
        jsonRes = jsonRes["context_info"]["conflicts"][0];
      }else{
        throw "Failed to create";
      }
    }else if (status >= 300) {
      throw "Failed to create";
    }
  }catch(e){
      const error = `Failed to create \n status: ${status}\n${responseTxt}`;
      throw error;
    }
  
  
  return jsonRes.id;
}

Download

Capture

Notes

  1. Folder ID is contained in the URL. https://{sub-domain}.app.box.com/folder/(Folder ID)
  2. The refresh token for Box has the expiration. Use regularly to ensure that it does not exceed the expiration. (60 days, as of July 2019. https://box-content.readme.io/docs/oauth-20)

%d bloggers like this: