Labels

Learn the powerful enterprise adaptable database:

Getting Started With ADABAS & Natural

Monday, February 1, 2016

1002 Handle Web Requests


.
1002 Handle Web Requests

How to write Google App Script to handle Web Requests

1) Create a spreadsheet

eg HandleWebRequest.

2) Open Code Editor within the spreadsheet

eg HandleWebRequest.

3) Edit the script

/*global var*/
var SCPID=ScriptApp.getScriptId(); /*script id*/
var SSTID=SpreadsheetApp.getActiveSpreadsheet().getId(); /*spreadsheet id*/
/*var DOCID=DocumentApp.getActiveDocument().getId();*/ /*document id*/
/*var FRMID=FormApp.getActiveForm().getId();*/ /*form id*/
var SSTFILE=DriveApp.getFileById(SSTID); /*get file*/
var Folders = SSTFILE.getParents(); /*get parent collection*/
var Folder = Folders.next(); /*get first parent item*/
var FOLID = Folder.getId(); /*get id for first parent item*/
/*log the global var*/
function logGlobalVar(){
Logger.log("script id:"+SCPID);
Logger.log("sheet id:"+SSTID);
Logger.log("folder id:"+FOLID);
}
/* web request listeners */
function doGet(e) {return handleResponse(e);}
function doPost(e) {return handleResponse(e);}
/* web request handler */
function handleResponse(e) {
  var lock = LockService.getPublicLock();
  lock.waitLock(30000); // wait 30 seconds before conceding defeat.
  try {
    var action = e.parameter.action;
    if (action == 'test') {
      return getTest(e);
    }      
  }
  catch (e) {/*if error return this*/return ContentService.createTextOutput(JSON.stringify({"result": "error","error": e})).setMimeType(ContentService.MimeType.JSON);}
  finally { /*release lock*/ lock.releaseLock();}  
}
/* test function */
function getTest(e){
  rows={a:1,b:2};
  var output = JSON.stringify({"result":"success", "value": rows});
    if (e.parameter.callback){
      // if error return this, again, in jsonp
      return ContentService
          .createTextOutput(e.parameter.callback+"("+ output + ");")
          .setMimeType(ContentService.MimeType.JAVASCRIPT);
    }
    else{
      return ContentService
          .createTextOutput(output)
          .setMimeType(ContentService.MimeType.JSON);
    }  
}

4) Publish as Web App

5) Access the URL

COPY:


.

No comments:

Post a Comment