UNPKG

fm-data-api

Version:

FileMaker Data Api wrapper for Vue.js

1 lines 15.7 kB
import axios from"axios";class Exception{constructor(message,code){if(code!==""){return"[ "+code+", "+message+" ]"}return"[ "+message+" ]"}}export class Response{constructor(headers,body){this.setHeaders(headers);this.body=body;this.RESPONSE_TYPE_JSON="json";this.RESPONSE_TYPE_TEXT="text";if(Array.isArray(body)){this.responseType=this.RESPONSE_TYPE_JSON}else{this.responseType=this.RESPONSE_TYPE_TEXT}}static get RESPONSE_TYPE_JSON(){return this.RESPONSE_TYPE_JSON}static get RESPONSE_TYPE_TEXT(){return this.RESPONSE_TYPE_TEXT}setHeaders(headers){if(Array.isArray(headers)){this.headers=headers;return this}throw new Exception("Bad headers","")}getHeader(header){if({}.propertyIsEnumerable.call(this.headers,header)&&this.headers[header].length>0){return this.headers[header]}throw new Exception("Header not found","")}static parse(hearders,body){return new Response(Response.parseHeaders(hearders),Response.parseBody(body))}getHttpCode(){let httpHeader=this.getHeader("Status");httpHeader=httpHeader.split(" ");return parseInt(httpHeader[1],10)}static parseHeaders(headers){headers=headers.split("\n");headers=headers.map(function(header){const exploded=header.split(":");return exploded.map(function(value){return value.trim().replace('"',"")})});headers=headers.filter(function(value){return(Array.isArray(value)?value[0]:value)!==""});const statusHeader=[];let index;for(index=0;index<headers.length;++index){const header={}.propertyIsEnumerable.call(headers,index)?headers[index]:[];if(!{}.propertyIsEnumerable.call(header,1)||header[1].length>0){break}if({}.propertyIsEnumerable.call(header,0)&&header[0].length>0){statusHeader.push({Status:header[0]});headers.splice(index,1)}}const processedHeaders=statusHeader;for(index=0;index<headers.length;++index){const header={}.propertyIsEnumerable.call(headers,index)?headers[index]:[];if(!{}.propertyIsEnumerable.call(header,1)||header[1].length<=0){continue}processedHeaders[header[0]]=header[1]}return processedHeaders}static parseBody(body){if(Response.isJson(body)){return JSON.parse(body)}return body}static isJson(string){try{JSON.parse(string)}catch(e){return false}return true}}export class AxiosClient{constructor(apiUrl){this.baseUrl=apiUrl}request(method,url,options,dataInfo=false){let completeUrl=encodeURI(this.baseUrl+url);let body="";var requestOptions={method:method,responseType:"json"};const axiosFM=axios.create();options.headers["Content-Type"]=options.headers["Content-Type"]===undefined?"application/json":options.headers["Content-Type"];options.headers.crossDomain=true;if({}.propertyIsEnumerable.call(options,"queryParams")){const queryParams=this.httpBuildQuery(options.queryParams);completeUrl+=queryParams.length>0?"?"+queryParams:""}requestOptions.url=completeUrl;if({}.propertyIsEnumerable.call(options,"json")&&method!=="GET"){body="{";for(const jsonOptionKey in options.json){if({}.propertyIsEnumerable.call(options.json,jsonOptionKey)){const jsonOptionData=options.json[jsonOptionKey];body+='"'+jsonOptionKey+'":'+(Response.isJson(jsonOptionData)?jsonOptionData:JSON.stringify(jsonOptionData))+","}}body=body.length>1?body.substring(0,body.length-1):body;body+="}";body=JSON.parse(body);if(body===false){throw new Exception("Failed to json encode parameters","")}}if(!{}.propertyIsEnumerable.call(options,"headers")){options.headers=[]}const myHeaders={};for(const headerKey in options.headers){if({}.propertyIsEnumerable.call(options.headers,headerKey)){const headerValue=options.headers[headerKey];const key=headerKey.replace('"',"").trim();myHeaders[key]=headerValue}}requestOptions.headers=myHeaders;if({}.propertyIsEnumerable.call(options,"fileObject")&&method==="POST"){var formdata=new FormData;formdata.append("upload",options.fileObject,options.fileObject.name);requestOptions.data=formdata}else if(typeof body!=="undefined"&&method!=="GET"){requestOptions.data=JSON.stringify(body)}axiosFM.interceptors.response.use(function(res){if(dataInfo){return res.data.response}if(res.data.response.data!==undefined){return res.data.response.data}if(res.data.response.recordId!==undefined){return res.data.response.recordId}if(res.data.response.modId!==undefined){return res.data.response.modId}if(res.data.response!==undefined){if(res.data.response.length===0){if(res.data.messages[0].code==="0"){return true}if(res.data.messages[0].code==="10"){return false}}return res.data.response}},function(error){if(error.config.url.includes("_find")&&error.response.data.messages[0].code==="401"){return{data:{},dataInfo:{foundCount:0}}}throw new Exception(error.response.data.messages[0].message,error.response.data.messages[0].code)});return axiosFM(requestOptions)}httpBuildQuery(paramsData){const searchParameters=new URLSearchParams;Object.keys(paramsData).forEach(function(parameterName){searchParameters.append(parameterName,paramsData[parameterName])});return searchParameters.toString()}}export default class DataApi{constructor(options={},logNow=true){this.SCRIPT_PREREQUEST="prerequest";this.SCRIPT_PRESORT="presort";this.SCRIPT_POSTREQUEST="postrequest";this.LASTVERSION="v1";this.initProperties();if({}.propertyIsEnumerable.call(options,"login")){this.apiUsername=options.login}if({}.propertyIsEnumerable.call(options,"version")){this.version=options.version}if({}.propertyIsEnumerable.call(options,"password")){this.apiPassword=options.password}if({}.propertyIsEnumerable.call(options,"oAuthRequestId")){this.oAuthRequestId=options.oAuthRequestId}if({}.propertyIsEnumerable.call(options,"oAuthIdentifier")){this.oAuthIdentifier=options.oAuthIdentifier}if({}.propertyIsEnumerable.call(options,"token")){this.apiToken=options.token}if({}.propertyIsEnumerable.call(options,"databaseName")){this.apiDatabase=options.databaseName}if({}.propertyIsEnumerable.call(options,"apiUrl")){this.ClientRequest=new AxiosClient(options.apiUrl)}if(!this.thereIsCredentials()||this.apiToken.length===0){new Exception("Data Api needs valid credentials [username;password] or [authRequestId;authIdentifier] or [token]","")}if(logNow){this.login()}}async login(){if(this.thereIsCredentials()){const headers=this.getHeaderAuth();return this.ClientRequest.request("POST","/"+this.version+"/databases/"+this.apiDatabase+"/sessions",{headers:headers,json:[]}).then(response=>{this.apiToken=response.token;return this})}return new Exception("Not available without credentials","")}logout(){this.ClientRequest.request("DELETE","/"+this.version+"/databases/"+this.apiDatabase+"/sessions/"+this.apiToken,[]);this.apiToken="";return this}validateSession(){const response=this.ClientRequest.request("GET","/"+this.version+"/validateSession",{headers:this.getDefaultHeaders()});return response}createRecord(layout,data,scripts=[],portalData={}){const jsonOptions=this.encodeFieldData(data);if(Object.keys(portalData).length>0){jsonOptions.portalData=this.encodePortalData(portalData)}this.prepareScriptOptions(scripts,jsonOptions);const response=this.ClientRequest.request("POST","/"+this.version+"/databases/"+this.apiDatabase+"/layouts/"+layout+"/records",{headers:this.getDefaultHeaders(),json:jsonOptions});return response}duplicateRecord(layout,recordId,scripts=[]){const response=this.ClientRequest.request("POST","/"+this.version+"/databases/"+this.apiDatabase+"/layouts/"+layout+"/records/"+recordId,{headers:this.getDefaultHeaders(),json:this.prepareScriptOptions(scripts)});return response.recordId}editRecord(layout,recordId,data,lastModificationId="",portalData={},scripts=[]){const jsonOptions=this.encodeFieldData(data);if(lastModificationId.length>0){jsonOptions.modId=lastModificationId}if(Object.keys(portalData).length>0){jsonOptions.portalData=this.encodePortalData(portalData)}this.prepareScriptOptions(scripts,jsonOptions);const response=this.ClientRequest.request("PATCH","/"+this.version+"/databases/"+this.apiDatabase+"/layouts/"+layout+"/records/"+recordId,{headers:this.getDefaultHeaders(),json:jsonOptions});return response.modId}deleteRecord(layout,recordId,scripts=[]){return this.ClientRequest.request("DELETE","/"+this.version+"/databases/"+this.apiDatabase+"/layouts/"+layout+"/records/"+recordId,{headers:this.getDefaultHeaders(),json:this.prepareScriptOptions(scripts)})}getRecord(layout,recordId,portals=[],scripts=[],responseLayout=""){const jsonOptions={};if(responseLayout.length>0){jsonOptions["layout.response"]=responseLayout}this.prepareScriptOptions(scripts,jsonOptions);this.preparePortalsOptions(portals,jsonOptions);const response=this.ClientRequest.request("GET","/"+this.version+"/databases/"+this.apiDatabase+"/layouts/"+layout+"/records/"+recordId,{headers:this.getDefaultHeaders(),queryParams:jsonOptions});return response}getRecords(layout,sort="",offset="",limit="",portals=[],scripts=[],dataInfo=false,responseLayout=""){const jsonOptions=this.prepareJsonOption({},offset,limit,sort,responseLayout,true);this.prepareScriptOptions(scripts,jsonOptions);this.preparePortalsOptions(portals,jsonOptions);return this.ClientRequest.request("GET","/"+this.version+"/databases/"+this.apiDatabase+"/layouts/"+layout+"/records",{headers:this.getDefaultHeaders(),queryParams:jsonOptions},dataInfo)}findRecords(layout,query,sort="",offset="",limit="",portals=[],scripts=[],dataInfo=false,responseLayout=""){let preparedQuery;if(!Array.isArray(query)){preparedQuery=[query]}else{preparedQuery=this.prepareQueryOptions(query)}const jsonOptions={query:JSON.stringify(preparedQuery)};this.prepareJsonOption(jsonOptions,offset,limit,sort,responseLayout);this.prepareScriptOptions(scripts,jsonOptions);this.preparePortalsOptions(portals,jsonOptions);const response=this.ClientRequest.request("POST","/"+this.version+"/databases/"+this.apiDatabase+"/layouts/"+layout+"/_find",{headers:this.getDefaultHeaders(),json:jsonOptions},dataInfo);return response}executeScript(layout,scriptName,scriptParam=""){const jsonOptions={};if(scriptParam.length>0){jsonOptions["script.param"]=scriptParam}const response=this.ClientRequest.request("GET","/"+this.version+"/databases/"+this.apiDatabase+"/layouts/"+layout+"/script/"+scriptName,{headers:this.getDefaultHeaders(),queryParams:jsonOptions});return response}uploadToContainer(layout,recordId,containerFieldName,containerFieldRepetition="",file){let containerFieldRepetitionFormat="";if(containerFieldRepetition.length>0){containerFieldRepetitionFormat="/"+parseInt(containerFieldRepetition)}const headers=this.getDefaultHeaders();headers["Content-Type"]="application/json";const response=this.ClientRequest.request("POST","/"+this.version+"/databases/"+this.apiDatabase+"/layouts/"+layout+"/records/"+recordId+"/containers/"+containerFieldName+containerFieldRepetitionFormat,{headers:headers,fileObject:file});return response}setGlobalFields(layout,globalFields){const response=this.ClientRequest.request("PATCH","/"+this.version+"/databases/"+this.apiDatabase+"/globals",{headers:this.getDefaultHeaders(),json:{globalFields:JSON.stringify(globalFields)}});return response}getProductInfo(){const response=this.ClientRequest.request("GET","/"+this.version+"/productInfo",{headers:this.getDefaultHeaders(),json:[]});return response}getDatabaseNames(){if(this.thereIsCredentials()){const response=this.ClientRequest.request("GET","/"+this.version+"/databases",{headers:this.getHeaderAuth(),json:[]});return response}return new Exception("Not available without credentials","")}getLayoutNames(){const response=this.ClientRequest.request("GET","/"+this.version+"/databases/"+this.apiDatabase+"/layouts",{headers:this.getDefaultHeaders(),json:[]});return response}getScriptNames(){const response=this.ClientRequest.request("GET","/"+this.version+"/databases/"+this.apiDatabase+"/scripts",{headers:this.getDefaultHeaders(),json:[]});return response}getLayoutMetadata(layout,recordId=""){const jsonOptions=[];let metadataFormat="/metadata";if(recordId.length>0){jsonOptions.recordId=recordId;metadataFormat=""}const response=this.ClientRequest.request("GET","/"+this.version+"/databases/"+this.apiDatabase+"/layouts/"+layout+metadataFormat,{headers:this.getDefaultHeaders(),json:jsonOptions});return response}getApiToken(){return this.apiToken}setApiToken(apiToken){this.apiToken=apiToken}setVersion(version){this.version=version}getDefaultHeaders(){return{Authorization:"Bearer "+this.apiToken}}getHeaderBasicAuth(){return{Authorization:"Basic "+btoa(this.apiUsername+":"+this.apiPassword)}}getHeaderOAuth(){return{"X-FM-Data-Login-Type":"oauth","X-FM-Data-OAuth-Request-Id":this.oAuthRequestId,"X-FM-Data-OAuth-Identifier":this.oAuthIdentifier}}getHeaderAuth(){let headers=[];if(this.apiUsername.length>0){headers=this.getHeaderBasicAuth()}if(this.oAuthRequestId.length>0){headers=this.getHeaderOAuth()}return headers}prepareQueryOptions(query){const item=[];if(Array.isArray(query)){for(let index=0;index<query.length;++index){const queryItem=query[index];if(!{}.propertyIsEnumerable.call(queryItem,"fields")){break}if(!Array.isArray(queryItem.fields)){if({}.propertyIsEnumerable.call(queryItem.fields,"fieldname")&&{}.propertyIsEnumerable.call(queryItem.fields,"fieldvalue")){const obj={};obj[queryItem.fields.fieldname.replace('"',"").trim()]=queryItem.fields.fieldvalue;item.push(obj)}}else{const objRequest={};for(const index in queryItem.fields){const fieldData=queryItem.fields[index];if({}.propertyIsEnumerable.call(fieldData,"fieldname")&&{}.propertyIsEnumerable.call(fieldData,"fieldvalue")){objRequest[fieldData.fieldname.replace('"',"").trim()]=fieldData.fieldvalue}else if({}.propertyIsEnumerable.call(fieldData,"omit")&&fieldData.omit){objRequest.omit="true"}}if(Object.entries(objRequest).length>0){item.push(objRequest)}}}}return item}prepareScriptOptions(scripts,jsonOptions={}){if(Array.isArray(scripts)){let index;const listType=[this.SCRIPT_POSTREQUEST,this.SCRIPT_PREREQUEST,this.SCRIPT_PRESORT];for(index=0;index<scripts.length;++index){const script=scripts[index];if(listType.indexOf(script.type)<0){continue}const scriptSuffix=!(script.type===this.SCRIPT_POSTREQUEST)?"."+script.type:"";jsonOptions["script"+scriptSuffix]=script.name;jsonOptions["script"+scriptSuffix+".param"]=script.param}}return jsonOptions}preparePortalsOptions(portals,jsonOptions={}){if(portals.length<=0){return[]}const portalList=[];let index;for(index=0;index<portals.length;++index){const portal=portals[index];portalList.push(portal.name);if({}.propertyIsEnumerable.call(portal,"offset")){const optionName="_offset."+portal.name;const obj={};obj[optionName.replace('"',"").trim()]=parseInt(portal.offset);jsonOptions[optionName]=portal.offset}if({}.propertyIsEnumerable.call(portal,"limit")){const optionName="_limit."+portal.name;const obj={};obj[optionName.replace('"',"").trim()]=parseInt(portal.limit);jsonOptions[optionName]=portal.limit}}jsonOptions.portal=JSON.stringify(portalList);return jsonOptions}encodeFieldData(data){return{fieldData:JSON.stringify(data)}}encodePortalData(portal){return JSON.stringify(portal)}prepareJsonOption(jsonOptions={},offset="",limit="",sort="",responseLayout="",withUnderscore=false){const additionalCharacter=withUnderscore?"_":"";if(sort.length>0){jsonOptions[additionalCharacter+"sort"]=Array.isArray(sort)?JSON.stringify(sort):sort}if(limit.length>0){jsonOptions[additionalCharacter+"limit"]=parseInt(limit)}if(offset.length>0&&parseInt(offset)>0){jsonOptions[additionalCharacter+"offset"]=parseInt(offset)}if(responseLayout.length>0){jsonOptions["layout.response"]=responseLayout}return jsonOptions}thereIsCredentials(){return this.apiUsername.length>0&&this.apiPassword.length>0||this.oAuthRequestId.length>0&&this.oAuthIdentifier.length>0}initProperties(){this.apiUsername="";this.apiPassword="";this.oAuthRequestId="";this.oAuthIdentifier="";this.apiToken="";this.apiDatabase="";this.ClientRequest="";this.version=this.LASTVERSION}}