Microsoft 365 OneDrive for Business: Create Folder
Creates a folder in the specified folder on OneDrive.
Configs: Common
  • Step Name
  • Note
Configs
  • C1: OAuth2 Setting *
  • C2: Parent Folder URL (Root Folder if blank)
  • C3: Folder Name to create *#{EL}
  • C4: Data item to save Folder URL
Script (click to open)

// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://login.microsoftonline.com/common/oauth2/v2.0/authorize
// - Token Endpoint URL: https://login.microsoftonline.com/common/oauth2/v2.0/token
// - Scope: https://graph.microsoft.com/Files.ReadWrite.All offline_access
// - Consumer Key: (Get by Microsoft Azure Active Directory)
// - Consumer Secret: (Get by Microsoft Azure Active Directory)

const GRAPH_URI = "https://graph.microsoft.com/v1.0/";

main();
function main(){
  //// == 工程コンフィグの参照 / Config Retrieving ==
  const oauth2 = configs.get("conf_OAuth2");
  const parentFolderUrl = retrieveParentFolderUrl();
  const folderName = retrieveFolderName();
  const urlDataDef = configs.getObject("conf_folderUrl");

  //// == 演算 / Calculating ==
  const parentFolderInfo = getFolderInfoByUrl( parentFolderUrl, oauth2 );
  const createdFolderUrl = createFolder( parentFolderInfo, folderName, oauth2 );

  //// == ワークフローデータへの代入 / Data Updating ==
  setData( urlDataDef, createdFolderUrl );
}

/**
  * configから値を読み出し、必要に応じて値チェックを行った後、値を返す
  * @return {String} configの値
  */
function retrieveParentFolderUrl() {
  const folderUrlDef = configs.getObject( "conf_parentFolderUrl" );
  let folderUrl = configs.get( "conf_parentFolderUrl" );
  if ( folderUrlDef !== null ) {
    folderUrl = engine.findData( folderUrlDef );
  }
  return folderUrl;
}

function retrieveFolderName() {
  const folderName = configs.get( "conf_folderName" );
  if ( folderName === "" || folderName === null ) {
    throw `Folder name is empty.`;
  }
  return folderName;
}

/**
  * フォルダのURLからフォルダ情報(ドライブIDとフォルダID)を取得し、
  * オブジェクトで返す(URLが空の場合はドライブIDをme/drive、フォルダIDをrootにする)
  * @param {String} folderUrl  フォルダのURL
  * @param {String} oauth2  OAuth2 設定名
  * @return {Object} folderInfo  フォルダ情報 {driveId, folderId}
  */
function getFolderInfoByUrl( folderUrl, oauth2 ) {
  let folderInfo = {driveId: "me/drive", folderId: "root"};
  if ( folderUrl !== "" && folderUrl !== null ) {
    // 分割代入
    const {
      id,
      parentReference: {
        driveId
      }
    } = getObjBySharingUrl( folderUrl, oauth2 );
    folderInfo = {driveId: `drives/${driveId}`, folderId: id};
  }
  return folderInfo;
}

/**
  * OneDriveのドライブアイテム(ファイル、フォルダ)のメタデータを取得し、JSONオブジェクトを返す
  * APIの仕様:https://docs.microsoft.com/ja-jp/onedrive/developer/rest-api/api/shares_get?view=odsp-graph-online
  * @param {String} sharingUrl  ファイルの共有URL
  * @param {String} oauth2  OAuth2 設定名
  * @return {Object} responseObj  ドライブアイテムのメタデータのJSONオブジェクト
  */
function getObjBySharingUrl( sharingUrl, oauth2 ) {
  if (sharingUrl === "" || sharingUrl === null) {
    throw `Sharing URL is empty.`;
  }

  // encoding sharing URL
  const encodedSharingUrl = encodeSharingUrl(sharingUrl);

  // API Request
  const response = httpClient.begin() // HttpRequestWrapper
    .authSetting(oauth2)
    .get( `${GRAPH_URI}shares/${encodedSharingUrl}/driveItem` ); // HttpResponseWrapper
  const httpStatus = response.getStatusCode();
  const responseStr = response.getResponseAsString();
  if (httpStatus >= 300) {
    engine.log(`---GET request--- ${httpStatus}\n${responseStr}\n`);
    throw `Failed to get drive item. status: ${httpStatus}`;
  }
  return JSON.parse( responseStr );
}

/**
  * 共有URLをunpadded base64url 形式にエンコードする
  * @param {String} sharingUrl  共有URL
  * @return {String} encodedSharingUrl  エンコードされた共有URL
  */
function encodeSharingUrl( sharingUrl ) {
  let encodedSharingUrl = base64.encodeToUrlSafeString( sharingUrl );
  while ( encodedSharingUrl.slice(-1) === '=' ) {
    encodedSharingUrl = encodedSharingUrl.slice(0,-1);
  }
  return `u!${encodedSharingUrl}`;
}

/**
  * フォルダを作成する
  * @param {String,String} driveId,folderId  親フォルダのドライブID、フォルダID
  * @param {String} folderName  作成するフォルダの名前
  * @param {String} oauth2  OAuth2 設定名
  * @return {String}  作成したフォルダの URL
  */
function createFolder( {
  driveId,
  folderId
}, folderName, oauth2 ){
  const url = `${GRAPH_URI}${driveId}/items/${folderId}/children`;
  const body = {
    "name": folderName,
    "folder":{},
    "@microsoft.graph.conflictBehavior": "fail" // 重複時はエラーになるように
  }
  const response = httpClient.begin()
    .authSetting(oauth2)
    .body(JSON.stringify(body), "application/json; charset=UTF-8")
    .post(url);
  //when error thrown
  const responseStr = response.getResponseAsString();
  const status = response.getStatusCode();
  if (status >= 300) {
    engine.log(`---POST request--- ${status}\n${responseStr}\n`);
    throw `Failed to create: ${folderName}. status: ${status}`;
  }
  const json = JSON.parse(responseStr);
  return json.webUrl;
}

/**
  * データ項目に出力する
  * @param {ProcessDataDefinitionView} dataDef  データ項目の ProcessDataDefinitionView
  * @param {String} dataString  出力する文字列
  */
function setData( dataDef, dataString ){
  if(dataDef !==  null){
    engine.setData( dataDef, dataString );
  }
}
  

Notes

  • This add-on is for OneDrive for Business of Microsoft 365. It does not work for OneDrive personal.
  • To get the URL of a file/folder on OneDrive, open the Details window of the file/folder by clicking the Information icon, proceed to “More details”, and click the icon next to “Path”.
    How to get URL of file/folder
  • If there are folder name conflicts, it returns error.

Capture

See also

Appendix

  • onedrive-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
%d bloggers like this: