Home > Mobile >  e.PostData with undefined objects in JSON with Google Apps Script
e.PostData with undefined objects in JSON with Google Apps Script

Time:10-02

I have this doPost web app which receives a JSON object from a payment gateway. It runs successfully when the contents are present but when the contents are empty or undefined, I get a Failed status in the execution logs in GAS.

I've tried a few different if statements to try to prevent the failed status but without success. Here is the doPost function, which includes an if statement.

if(typeof e.postData === "undefined") return;

Can anyone suggest a solution to skip execution if the e.postData is equal to "undefined"?

function doPost(e) {
  const jsonString = e.postData.getDataAsString();
  const event = JSON.parse(jsonString)
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName("Import");
  const ts = new Date();
  const time = Utilities.formatDate(ts, "GMT 1", "dd/MM/yyyy, h:mm a");
  const nextRow = sh.getLastRow()   1;
  if(typeof e.postData === "undefined") return;
  sh.getRange(nextRow, 1).setValue(time);
  sh.getRange(nextRow, 2, 1, 7).setValues([[jsonString, event.data.risk.flagged, event.type, event.data.reference, event.data.amount, event.data.currency, event.data.customer.email]]);
}

Thanks for reading.

CodePudding user response:

The test should probably be the first thing in the function. Take advantage of console.log() when debugging. Try this at the start of the function:

function doPost(e) {
  if (!e) {
    throw new Error('Do not run the doPost(e) function in the script editor window.');
  }
  if (!e.postData || e.postData === 'undefined') {
    console.log('e.postData is missing')
    return;
  }
  // debugging
  console.log('e.postData: '   JSON.stringify(e.postData));
  console.log('getDataAsString()): '   JSON.stringify(e.postData.getDataAsString()));
  console.log("getDataAsString('UTF-8')"   JSON.stringify(e.postData.getDataAsString('UTF-8')));
  // ...

CodePudding user response:

I've found the issue, after trial and error, I've made each element in the returned array optional by using the question marks; here is an example of the optional elements:

event.data?.risk?.flagged

The final code is shown below. Some elements were not included in the postData, such as the one above. This could be TRUE, FALSE or null.

    function doPost(e) {
  const jsonString = e.postData.getDataAsString();
  const event = JSON.parse(jsonString)
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName("Import");
  const ts = new Date();
  const time = Utilities.formatDate(ts, "GMT 1", "dd/MM/yyyy, h:mm a");
  const nextRow = sh.getLastRow()   1;
  sh.getRange(nextRow, 1).setValue(time);
  sh.getRange(nextRow, 2, 1, 7).setValues([[jsonString, event.data?.risk?.flagged, event.type, event.data?.reference, event.data?.amount, event.data?.currency, event.data?.customer.email]]); 
  getData()
}
  • Related