Created
January 10, 2022 06:40
-
-
Save goforbg/e076acb6b72a9c36c3f0b7afc5c6742f to your computer and use it in GitHub Desktop.
Save formdata automatically onto google spread sheets
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
// req = HTTP incoming message, res = HTTP server response | |
export default async function handler(req, res) { | |
try { | |
if (req.method === "POST") { | |
// Process a POST request | |
if (!req.body) { | |
return res.status(403).send("Forbidden"); | |
} | |
if (!req.body.name || !req.body.email) { | |
return res.status(400).send("Invalid Request"); | |
} | |
const validEmailRegex = | |
/^((?!\.)[\w\-_.]*[^.])(@\w+)(\.\w+(\.\w+)?[^.\W])$/; | |
const { name, email } = req.body; | |
if (!validEmailRegex.test(email)) { | |
return res.status(403).send("Forbidden : Invalid Email."); | |
} | |
const { GoogleSpreadsheet } = require("google-spreadsheet"); | |
// Initialize the sheet - doc ID is the long id in the sheets URL | |
const doc = new GoogleSpreadsheet( | |
process.env.GOOGLE_NATS_EARLY_ACCESS_SHEETS_ID | |
); | |
// Initialize Auth - see https://theoephraim.github.io/node-google-spreadsheet/#/getting-started/authentication | |
await doc.useServiceAccountAuth({ | |
// env var values are copied from service account credentials generated by google | |
// see "Authentication" section in docs for more info | |
client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL, | |
private_key: process.env.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY.replace( | |
/\\n/g, | |
"\n" | |
) | |
}); | |
await doc.loadInfo(); | |
const sheet = doc.sheetsByIndex[0]; | |
const newRow = await sheet.addRow({ ...req.body }); | |
return res.status(200).json({ message: "Saved info!" }); | |
} else { | |
// Handle any other HTTP method | |
return res.status(403).send("Forbidden"); | |
} | |
} catch (err) { | |
console.log(err); | |
return res.status(500).send("Unable to process your information"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment