OpenMBEE MMSのREST APIを使う

#はじめに
OpenMBEEのMMSのREST-APIをJavascriptで使う方法をサンプルコードをベースに記載します。
http://www.openmbee.org/

OpenMBEEやMMSとは何ぞやという人がほとんどかと思いますが、REST-APIをJavascriptで使うサンプルと思っていただければと。

比較的新しいJavascriptでの書き方を目指しており(ES6)、varやfunctionは使わないようにしています。

#HTML
HTML部分は以下になります。
\<div>の部分にAPIで取得したデータを表示していくだけです。

```html
<html lang="ja">

<h1>Display Debug URL</h1>
<div id="testUrl"></div>

<h1>orgs</h1>
<div id="orgs"></div>
<div id="orgs2"></div>
<div id="orgInput"></div>

<h1>projects</h1>
<div id="projects"></div>

<h1>refs</h1>
<div id="refs"></div>

<h1>documents</h1>
<div id="documents"></div>

<h1>elements</h1>
<div id="elements"></div>

</html>
```

#認証
MMSのREST-APIはBASIC認証(のようなもの?)がかかっているのでHTTPヘッダに加える認証情報を作成します。(Javascriptのコードになります)
MMSに限らず、BASIC認証がかかっているサイトでREST-APIを使う場合はこの方法で行けます(多分)
"admin:admin"の部分がユーザ名とパスワードになります。

```javascript

	const sServerUrl = "[[サーバURL]]";
	
	const Base64_encode = (str) => {
		return btoa(unescape(encodeURIComponent(str)));
	};
	
	const sAuth = Base64_encode("admin:admin");
	console.log(sAuth);
```

#API
##GET
Organizationの一覧を取得するAPIです。引数なしのREST-APIです。
dispOrgs関数で取得したJSONを表示しますが、この関数の実装は後のほうに記載してあります。

```javascript
	/**
	 * Get Organization
	 */
	const getOrgs = () => {
		const url = `http://${sServerUrl}/alfresco/s/orgs`;
		console.log(url);
		document.getElementById("testUrl").textContent = url;
		
		const myHeaders = new Headers();
		myHeaders.set("Authorization", `Basic ${sAuth}`);
		console.log(myHeaders.get("Authorization"));
		
		const req = new Request(url,{
			method : "GET"
			,headers: myHeaders
			,mode: "cors"
		});
		
		fetch(req).then((response) => {
			return response.json();
		}).then((json) => {
			console.log(json);
			console.log(json.orgs);
			console.log(json.orgs.length);
			dispOrgs(json);
		})
	};
```

projectの一覧を取得するAPIです。

```javascript

	/**
	 * get projects 
	 * @param orgId
	 */
	const getProjects = (orgId) => {
		const url = `http://${sServerUrl}/alfresco/s/orgs/${orgId}/projects`;
		console.log(url);
		document.getElementById("restUrl").textContent = url;
		
		const myHeaders = new Headers();
		myHeaders.set("Authorization", `Basic ${sAuth}`);
		console.log(myHeaders.get("Authorization"));
		
		const req = new Request(url,{
			method : "GET"
			,headers: myHeaders
			,mode: "cors"
		});
		
		fetch(req).then((response) => {
			return response.json();
		}).then((json) => {
			console.log(json);
			dispProjects(json,orgId);
		})
	};
```

refsを取得するAPIです。(ブランチの一覧が取れるようです)

```javascript

	/**
	 * get refs
	 * @param projectId
	 */
	const getRefs = (projectId) => {
		const url = `http://${sServerUrl}/alfresco/s/projects/${projectId}/refs`;
		console.log(url);
		document.getElementById("restUrl").textContent = url;
		
		const myHeaders = new Headers();
		myHeaders.set("Authorization", `Basic ${sAuth}`);
		console.log(myHeaders.get("Authorization"));
		
		const req = new Request(url,{
			method : "GET"
			,headers: myHeaders
			,mode: "cors"
		});
		
		fetch(req).then((response) => {
			return response.json();
		}).then((json) => {
			console.log(json);
			//document.getElementById("refs").textContent = JSON.stringify(json);
			dispRefs(json);
		})
	};
```

documentの一覧を取得するAPIです

```javascript

	/**
	 * get documents
	 * @param projectId
	 */
	const getDocuments = (projectId,refId) => {
		const url = `http://${sServerUrl}/alfresco/s/projects/${projectId}/refs/${refId}/documents`;
		console.log(url);
		document.getElementById("restUrl").textContent = url;
		
		const myHeaders = new Headers();
		myHeaders.set("Authorization", `Basic ${sAuth}`);
		console.log(myHeaders.get("Authorization"));
		
		const req = new Request(url,{
			method : "GET"
			,headers: myHeaders
			,mode: "cors"
		});
		
		fetch(req).then((response) => {
			return response.json();
		}).then((json) => {
			console.log("DocumentJson");
			console.log(json);
			//document.getElementById("documents").textContent = JSON.stringify(json);
			dispDocuments(json);
		})
	};
	
```

artifactの一覧を取得するAPIです。

```javascript

	/**
	 * get artifacts
	 * @param projectId
	 * @param refId
	 */
	const getArtifacts = (projectId,refId) => {
		const url = `http://${sServerUrl}/alfresco/s/projects/${projectId}/refs/{refId}/artifacts`;
		console.log(url);
		document.getElementById("restUrl").textContent = url;
		
		const myHeaders = new Headers();
		myHeaders.set("Authorization", `Basic ${sAuth}`);
		console.log(myHeaders.get("Authorization"));
		
		const req = new Request(url,{
			method : "GET"
			,headers: myHeaders
			,mode: "cors"
		});
		
		fetch(req).then((response) => {
			return response.json();
		}).then((json) => {
			console.log("ArtifactJson");
			console.log(json);
		})
		
	};
```

elementの一覧を取得するAPIです。

```javascript

	/**
	 * get elements
	 * @param projectId
	 * @param refId
	 */
	const getElements = (projectId,refId) => {
		const url = `http://${sServerUrl}/alfresco/s/projects/${projectId}/refs/${refId}/elements`;
		console.log(url);
		document.getElementById("restUrl").textContent = url;
		
		const myHeaders = new Headers();
		myHeaders.set("Authorization", `Basic ${sAuth}`);
		console.log(myHeaders.get("Authorization"));
		
		const req = new Request(url,{
			method : "GET"
			,headers: myHeaders
			,mode: "cors"
		});
		
		fetch(req).then((response) => {
			return response.json();
		}).then((json) => {
			console.log("ElementJson");
			console.log(json);
			dispElements(json);
		})
		
	};
```

```javascript

	/**
	 * get ids of elements based on view relationship
	 * @param projectId
	 * @param refId
	 * @param elementId
	 */
	const getCfids = (projectId,refId,elementId) => {
		const url = `http://${sServerUrl}/alfresco/s/projects/${projectId}/refs/${refId}/elements/${elementId}/cfids`;
		console.log(url);
		document.getElementById("restUrl").textContent = url;
		
		const myHeaders = new Headers();
		myHeaders.set("Authorization", `Basic ${sAuth}`);
		console.log(myHeaders.get("Authorization"));
		
		const req = new Request(url,{
			method : "GET"
			,headers: myHeaders
			,mode: "cors"
		});
		
		fetch(req).then((response) => {
			return response.json();
		}).then((json) => {
			console.log("CfidsJson");
			console.log(json);
			dispCfids(json);
		})
		
	};
```

##DISP
DISPの項ではAPIの説明ではなく、APIでGetしたものをブラウザに表示するための関数を記載します。
orgとprojectは1対nの関係になっているため、dispOrgsではorgの一覧を表示しますが、クリックするとorgを引数にしてgetProjectを呼び出すようにしています。慣れていないのでfunctionを使わずアロー関数でこれを行うことに苦労しました。

```javascript
	/**
	 * disp org
	 */
	const dispOrgs = (orgJson) => {
		let sOrgRow = "";
		let arrOrgId = [];
		for (const oOrg of orgJson.orgs) {
			sOrgRow = `${sOrgRow}<tr><td><a href="javascript:void(0);" id="orgId_${oOrg.id}">${oOrg.id}</a></td><td>${oOrg.name}</td></tr>`;
			arrOrgId.push(oOrg.id);
		}
		const sHtml = `<table>${sOrgRow}</table>`;
		document.getElementById("orgs").innerHTML = sHtml;
		
		//const sHtml2 = `<input type="text" id="org"></input><input type="button" value="getProjects" onclick="";></input>`;
		//document.getElementById("orgInput").innerHTML = sHtml2;
		
		for(const sOrdId of arrOrgId){
			const sId = `orgId_${sOrdId}`;
			document.getElementById(sId).onclick = () => {
				console.log(sOrdId);
				getProjects(sOrdId);
			};
			
		}
	};
	
	/**
	 * disp projects
	 */
	const dispProjects = (prjJson,orgId) => {
		document.getElementById("prj_orgId").innerHTML = `orgId= ${orgId}`;
		
		let sRow = "";
		let arrPrgId = [];
		for (const oPrj of prjJson.projects) {
			sRow = `${sRow}<tr><td><a href="javascript:void(0);" id="prjId_${oPrj.id}">${oPrj.id}</a></td><td>${oPrj.name}</td></tr>`;
			arrPrgId.push(oPrj.id);
		}
		const sHtml = `<table>${sRow}</table>`;
		document.getElementById("projects").innerHTML = sHtml;
		
		for(const sPrjId of arrPrgId){
			const sId = `prjId_${sPrjId}`;
			document.getElementById(sId).onclick = () => {
				console.log(sPrjId);
				getRefs(sPrjId);
				gProjectId = sPrjId;
			};
		}
	};
	/**
	 * disp Refs
	 */
	 const dispRefs = (refJson) => {
	 	document.getElementById("ref_projectId").innerHTML = `ProjectId= ${gProjectId}`;
	 	
	 	let sRow = "";
	 	let arrRefId = [];
		for (const oRef of refJson.refs) {
			sRow = `${sRow}<tr class="table1">`;
			sRow = `${sRow}<td class="table1"><a href="javascript:void(0);" id="refId_doc_${oRef.id}">d</a></td>`;
			sRow = `${sRow}<td class="table1"><a href="javascript:void(0);" id="refId_art_${oRef.id}">a</a></td>`;
			sRow = `${sRow}<td class="table1"><a href="javascript:void(0);" id="refId_${oRef.id}">${oRef.id}</a></td>`;
			sRow = `${sRow}<td>${oRef.name}</td>`;
			sRow = `${sRow}</tr>`;
			arrRefId.push(oRef.id);
		}
		const sHtml = `<table class="table1">${sRow}</table>`;
		document.getElementById("refs").innerHTML = sHtml;
		
		for(const sRefId of arrRefId){
			const sId = `refId_${sRefId}`;
			document.getElementById(sId).onclick = () => {
				console.log(sRefId);
				getElements(gProjectId,sRefId);
				gRefsId = sRefId;
			};
		}
	};
	/**
	 * disp Documents
	 */
	 const dispDocuments = (docJson) => {
	 	let sRow = "";
		for (const oDoc of docJson.documents) {
			sRow = `${sRow}<tr><td><a href="javascript:document.getElementById('org').value='${oDoc.id}';void(0);">${oDoc.id}</a></td><td>${oDoc.name}</td></tr>`;
		}
		const sHtml = `<table>${sRow}</table>`;
		document.getElementById("documents").innerHTML = sHtml;
	 };
	/**
	 * disp Elements
	 */
	const dispElements = (elemJson) => {
		let arrElemId = [];
	
		let sRow = "<tr><th>id</th><th>name</th><th>type</th><th>ownerId</th><th>value type</th><th>value name</th><th>value</th></tr>";
		for (const oElem of elemJson.elements) {
			sRow = `${sRow}<tr class="table1"><td class="table1"><a href="javascript:void(0);" id="elemId_${oElem.id}">${oElem.id}</a></td><td>${oElem.name}</td>`;
			sRow = `${sRow}<td class="table1">${oElem.type}</td><td class="table1">${oElem.ownerId}</td>`;
			if(typeof oElem.value !== 'undefined'){
				let oElementValueType = "";
				let oElementValueName = "";
				let oElementValue = "";
				for (const oValue of oElem.value) {
					oElementValueType = `${oElementValueType}<div>${oValue.type}</div>`;
					oElementValueName = `${oElementValueName}<div>${oValue.name}</div>`;
					oElementValue = `${oElementValue}<div>${oValue.value}</div>`;
				}
				sRow = `${sRow}<td class="table1">${oElementValueType}</td><td class="table1">${oElementValueName}</td><td class="table1">${oElementValue}</td><tr>`;
			}else{
				sRow = `${sRow}<td class="table1">Undef Value</td><td class="table1"></td><td class="table1"></td><tr>`;
			}
			arrElemId.push(oElem.id);
		}
		const sHtml = `<table class="table1">${sRow}</table>`;
		document.getElementById("elements").innerHTML = sHtml;
		
		for(const sElemId of arrElemId){
			const sId = `elemId_${sElemId}`;
			document.getElementById(sId).onclick = () => {
				console.log(sElemId);
				getCfids(gProjectId,gRefsId,sElemId);
			};
		}
		
	 };
	 
	/**
	 * disp cfids
	 */
	const dispCfids = (cfidsJson) => {
		
		let sRow = "";
		for (const oCfids of cfidsJson.elementIds) {
			sRow = `${sRow}<tr><td><a href="javascript:void(0);">${oCfids}</a></td></tr>`;
		}
		const sHtml = `<table>${sRow}</table>`;
		
		document.getElementById("cfids").innerHTML = sHtml;
	};
```

##POST
POSTのAPIは・・・あまり調べていません。OrgとProjectの登録の2つです。
jsonを送るとjsonの内容に沿って登録されます。
ここで記載するコードは、登録するjsonがコード内にべた書きです。

```javascript
	/**
	 * Post Organizations 
	 */
	const postOrgs = () => {
		const url = `http://${sServerUrl}/alfresco/s/orgs`;
		console.log(url);
		document.getElementById("restUrl").textContent = url;
		
		const oJson = {"orgs": [{"id": "vetest", "name": "vetest"},{"id": "vetest2", "name": "vetest2"}]};
		
		const oBody = JSON.stringify(oJson);
		const myHeaders = new Headers();
		myHeaders.set("Authorization", `Basic ${sAuth}`);
		myHeaders.set("Content-Type", "application/json");
		
		//console.log(myHeaders.get("Authorization"));
		console.log("POST JSON");
		console.log(oJson);
		console.log(oBody);
		const req = new Request(url,{
			method : "POST"
			,headers: myHeaders
			,mode: "cors"
			,body : oBody
		});
		
		fetch(req).then((response) => {
			return response.json();
		}).then((json) => {
			console.log(json);
		})
	};
	
```


```javascript

	/**
	 * Post Projects
	 * @param orgId
	 */
	const postProjects = (orgId) => {
		const url = `http://${sServerUrl}/alfresco/s/orgs/${orgId}/projects`;
		console.log(url);
		document.getElementById("restUrl").textContent = url;
		
		const oJson = {"projects": [{"type":"Project","id": "vetestPrj", "name": "vetestPrj"},{"type":"Project","id": "vetestPrj2", "name": "vetestPrj2"}]};
		
		const oBody = JSON.stringify(oJson);
		const myHeaders = new Headers();
		myHeaders.set("Authorization", `Basic ${sAuth}`);
		myHeaders.set("Content-Type", "application/json");
		
		//console.log(myHeaders.get("Authorization"));
		console.log("POST JSON");
		console.log(oJson);
		console.log(oBody);
		const req = new Request(url,{
			method : "POST"
			,headers: myHeaders
			,mode: "cors"
			,body : oBody
		});
		
		fetch(req).then((response) => {
			return response.json();
		}).then((json) => {
			console.log(json);
		})
	};
```