Created
May 16, 2019 23:41
-
-
Save bots-business/b627418423a2c5df3b4ed329181077f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sheet; | |
//this is a function that fires when the webapp receives a GET request | |
function doGet(e) { | |
var prms = e.parameter; | |
var result = {}; | |
result.headers = tableHeaders(prms.sheetName); | |
if(prms.rowIndex){ | |
result.row = getRow(prms.rowIndex); | |
} | |
return renderText(JSON.stringify(result)); | |
} | |
//this is a function that fires when the webapp receives a POST request | |
function doPost(e) { | |
var params = JSON.stringify(e.postData.contents); | |
params = JSON.parse(params); | |
var myData = JSON.parse(e.postData.contents); | |
var sheetName = myData.sheetName; | |
sheet = getSheet(sheetName); | |
newRow = myData.row; | |
if(myData.rowIndex){ | |
result = insertRow(newRow, parseInt(myData.rowIndex)); | |
}else{ | |
result = addRow(newRow); | |
} | |
SpreadsheetApp.flush(); | |
return renderText(JSON.stringify(result)); | |
} | |
function renderText(text){ | |
text = encodeURI(text); | |
return HtmlService.createHtmlOutput("APP-RESULT" + text + "APP-RESULT"); | |
} | |
function renderError(text){ | |
renderText(text); | |
throw text; | |
} | |
function getSheet(sheetName){ | |
if(sheet){ return sheet } | |
sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName); | |
if(!sheet){ | |
renderError("No sheet with name: " + sheetName); | |
} | |
return sheet; | |
} | |
function rows(sheetName){ | |
return getSheet(sheetName).getDataRange().getValues(); | |
} | |
function tableHeaders(sheetName){ | |
return rows(sheetName)[0]; | |
} | |
function addRow(data){ | |
var lastRow = Math.max(sheet.getLastRow(), 1); | |
sheet.insertRowAfter(lastRow); | |
lastRow = lastRow + 1; | |
return insertRow(data, lastRow); | |
} | |
function insertRow(data, rowIndex){ | |
var rows = sheet.getDataRange().getValues(); | |
var headers = rows[0]; | |
var cell_index = 1; | |
var key; | |
var inserted = 0; | |
for(var it in headers){ | |
key = headers[it] | |
if(data[key]){ | |
sheet.getRange(rowIndex, cell_index).setValue(data[key]); | |
inserted = inserted + 1; | |
} | |
cell_index=cell_index + 1; | |
} | |
return { rowIndex: rowIndex, inserted: inserted } | |
} | |
function getRow(rowIndex){ | |
var rows = sheet.getDataRange().getValues(); | |
var headers = rows[0]; | |
var cell_index = 1; | |
var key; | |
var result = {}; | |
for(var it in headers){ | |
key = headers[it] | |
result[key]=sheet.getRange(rowIndex, cell_index).getValue(); | |
cell_index=cell_index + 1; | |
} | |
result.rowIndex = rowIndex; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
not work