Last active
April 12, 2022 18:16
-
-
Save CS-5/5db243cb25c26c903d2921ec68e66583 to your computer and use it in GitHub Desktop.
Google Sheets script to add rows via POST request (JSON or form payload). Only accepts fields that are valid columns on the sheet.
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
/* === Configuration === */ | |
// The sheet to work with | |
const SHEET = SpreadsheetApp | |
.openById("FILE ID") | |
.getSheetByName("SHEET NAME"); | |
// Create list of headings | |
const COLUMNS = SHEET.getRange(1, 1, 1, SHEET.getLastColumn()).getValues()[0].map(v => v.toString().toLowerCase()); | |
// The email to send to (if enabled) | |
const EMAIL = { | |
enable: false, | |
to: "[email protected]", | |
subject: "New Entry!", | |
}; | |
/* === Functions === */ | |
const doGet = () => { | |
return ContentService.createTextOutput("API is working").setMimeType(ContentService.MimeType.JSON); | |
} | |
const doPost = (request = {}) => { | |
const { postData: { contents, type } = {} } = request; | |
let entry = Array(COLUMNS.length); | |
// Handle JSON or form inputs | |
switch (type) { | |
case "application/json": | |
Object.entries(JSON.parse(contents)).forEach(([k, v]) => { | |
insertIfColumn(k.toLowerCase(), v, entry, COLUMNS); | |
}) | |
break; | |
case "application/x-www-form-urlencoded": | |
contents | |
.split("&") | |
.map((i) => i.split("=")) | |
.forEach(([k, v]) => { | |
insertIfColumn(k.toLowerCase(), v, entry, COLUMNS); | |
}); | |
break; | |
} | |
// Make sure there was valid data to enter | |
if (typeof entry !== "undefined") { | |
SHEET.appendRow(entry); | |
if (EMAIL.enable) { | |
MailApp.sendEmail({ | |
to: EMAIL.to, | |
subject: EMAIL.subject, | |
htmlBody: "Entry content: " + JSON.stringify(entry), | |
}); | |
} | |
} | |
// Return the data entered | |
return ContentService.createTextOutput(JSON.stringify(entry)).setMimeType(ContentService.MimeType.JSON); | |
}; | |
// Helper function to to build array based on columns | |
const insertIfColumn = (key, value, array, columns) => { | |
if (columns.includes(key)) { | |
array.splice(columns.indexOf(key), 1, value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment