Labels

Learn the powerful enterprise adaptable database:

Getting Started With ADABAS & Natural

Monday, February 1, 2016

10031 Handle REST Service


.
This is a simplified version of the previous tutorial, http://basic-steps.blogspot.my/2016/02/1003-handle-rest-service.html.

10031 Handle REST Service
How to write Google App Script to handle REST Service

Objective

1. Create generic record utility functions
        addPerson()
2. Create record utility manager ie manageRecord()

1) Create a spreadsheet

eg HandleRestService.
Create  a sheet “persons”.
Set the first row as follows.
firstname
lastname
email

2) Open Code Editor within the spreadsheet

eg HandleRestService.

3) Edit the Script

Add the following script to Code.gs file
/*global var*/
var SCPID=ScriptApp.getScriptId(); /*script id*/
var SST=SpreadsheetApp.getActiveSpreadsheet(); /*active spreadsheet */
var SSTID=SpreadsheetApp.getActiveSpreadsheet().getId(); /*spreadsheet id*
/

/* web request listeners */
function doGet(e) {return handleResponse(e);}
function doPost(e) {return handleResponse(e);}


/* handle action request */
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
 try {
   var action = e.parameter.action;
   if (action == 'addperson') {
     return manageRecords("addperson",e); //records command,parameter
   }
 }
catch (e) {/*if error return this*/return ContentService.createTextOutput(JSON.stringify({"result": "error","error": e})).setMimeType(ContentService.MimeType.JSON);}
finally { /*release lock*/ lock.releaseLock();}
}


/* handle records command */
function manageRecords(command,e){
 var output;
 switch (command){  
   case "addperson":
     output=addPerson(e);
     break;        
 }
 return ContentService
 .createTextOutput(JSON.stringify(output))
 .setMimeType(ContentService.MimeType.JSON);
}

function addPerson(e) {
 var Sheet = SST.getSheetByName("person");
 try {
   var headers = Sheet.getRange(1, 1, 1, Sheet.getLastColumn()).getValues()[0];
   var rownum = Sheet.getLastRow() + 1; // get next row
   var row = [];
   // loop through the header columns
   for (colno in headers) {
           row.push(e.parameter[headers[colno]]);
     }
   Sheet.getRange(rownum, 1, 1, row.length).setValues([row]);
   // return json success results with the row number of the newly added record
   return rownum
   } catch (e) {
     // if error return this
     return 0
     }
}
3a. Publish and Deploy the codes as web app.
3b. Set the permission.

4) Prepare FrontEnd Codes

The front-end could be using any scripting language like PHP or simple HTML and JavaScript with XmlHttpRequest command.
<form id="formAddPerson" name="formAddPerson" onsubmit="submitForm(this)">
<input type="hidden" name="action" value="addperson">
<input name="firstname" type="text" value=""  placeholder="First Name" />
<input name="lastname" type="text" value=""  placeholder="Last Name"/>
<input name="email" type="text" value=""  placeholder="Email"/>
<p id="StatusMessage"></p>
<input type="submit" value="add person" />
</form>
<hr/>
<script>
/*utility functions*/
function formToJson(form){var obj={};var elements=form.querySelectorAll("input, select, textarea");for(var i=0;i<elements.length;++i){var element=elements[i];var name=element.name;var value=element.value;if(name){obj[name]=value;}} return obj;}
function jsonToUrlParameters(json){return Object.keys(json).map((i)=>i+'='+json[i]).join('&');}
var url='https://script.google.com/macros/s/AKfycbyPJwX7s5FRRNN1vYPzSdhFfdk_0c4ijoYqxr-fW6VHJ6o_-3g/exec?';

/* uses POST Request*/
function submitForm(frmPerson){
  /*prevent the onsubmit default event*/
  if(event.preventDefault){event.preventDefault();}
  /*convert FormData to JsonData*/
  /*convert JsonData to RequestParameter*/
  var requestparameters=jsonToUrlParameters(formToJson(frmPerson));
  //console.log(requestparameters);
  /*display status message*/
  document.getElementById("StatusMessage").innerHTML = "sending request to server...";
  /*create XmlHttpRequest (xhr) object */
   var xhr = new XMLHttpRequest();
  /*open xhr connection, define method and url*/
  xhr.open("POST", url, true);
  //Send the proper header information along with the request
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  
  /*send xhr*/
  xhr.send(requestparameters);
  /*when xhr response is ready, execute function*/
  xhr.onreadystatechange = function() {
  if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
  console.log(xhr.responseText);
  /*reset form*/
  frmPerson.reset();
  }/*if xhr.readyState*/
  }/*xhr.onreadystatechange*/  
}/*submitForm*/
</script>
  </body>
You can copy-paste the code to www.codepen.io to test the outcome as shown below.

EXAMPLE:


No comments:

Post a Comment