Guest User

Script Google Sheets Autosave

a guest
Apr 11th, 2025
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. function doPost(e) {
  2. Logger.log("== doPost DIPANGGIL ==");
  3.  
  4. try {
  5. // Log mentah dari body POST
  6. const raw = e.postData.contents;
  7. Logger.log("Raw Payload: " + raw);
  8.  
  9. const a = JSON.parse(raw);
  10. Logger.log("Parsed JSON: " + JSON.stringify(a));
  11.  
  12. if (!a || typeof a !== "object" || Array.isArray(a)) {
  13. Logger.log("ERROR: JSON tidak valid atau kosong");
  14. throw new Error("Invalid or empty JSON object");
  15. }
  16.  
  17. const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  18. Logger.log("Spreadsheet dibuka");
  19.  
  20. const keys = Object.keys(a);
  21. Logger.log("Keys ditemukan: " + keys.join(", "));
  22.  
  23. if (keys.length === 0) {
  24. Logger.log("ERROR: Tidak ada keys");
  25. throw new Error("No data keys provided");
  26. }
  27.  
  28. const lastCol = sheet.getLastColumn();
  29. Logger.log("Last Column: " + lastCol);
  30.  
  31. let header = [];
  32.  
  33. if (lastCol === 0) {
  34. Logger.log("Sheet kosong, header akan dibuat");
  35. header = keys;
  36. sheet.appendRow(header);
  37. } else {
  38. Logger.log("Ambil header dari baris 1");
  39. header = sheet.getRange(1, 1, 1, lastCol).getValues()[0];
  40. }
  41.  
  42. Logger.log("Header: " + header.join(", "));
  43.  
  44. const row = header.map(h => a[h] !== undefined ? a[h] : "");
  45. Logger.log("Row yang akan ditulis: " + row.join(", "));
  46.  
  47. sheet.appendRow(row);
  48. Logger.log("Row berhasil ditambahkan");
  49.  
  50. const response = {
  51. status: "success",
  52. received: a
  53. };
  54.  
  55. Logger.log("Mengirim response sukses: " + JSON.stringify(response));
  56. return ContentService
  57. .createTextOutput(JSON.stringify(response))
  58. .setMimeType(ContentService.MimeType.JSON);
  59.  
  60. } catch (err) {
  61. Logger.log("CATCH ERROR: " + err.message);
  62.  
  63. const responseError = {
  64. status: "error",
  65. message: err.message
  66. };
  67.  
  68. return ContentService
  69. .createTextOutput(JSON.stringify(responseError))
  70. .setMimeType(ContentService.MimeType.JSON);
  71. }
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment