sayanriju

Untitled

Jan 14th, 2021
395
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const BusBoy = require("busboy")
  2. if (process.env.NODE_ENV === "development") {
  3.   // eslint-disable-next-line global-require, import/no-extraneous-dependencies
  4.   require("yamlenv").config()
  5. }
  6.  
  7. const mailer = require("./lib/mailer")
  8.  
  9. exports.handler = (req, res) => {
  10.   // Enable CORS:
  11.   res.set("Access-Control-Allow-Origin", "*")
  12.   res.set("Access-Control-Allow-Methods", "GET, POST")
  13.  
  14.   const busboy = new BusBoy({ headers: req.headers })
  15.   const fields = {}
  16.   const attachment = {
  17.     filename: "",
  18.     content: null
  19.   }
  20.   let subject = "[[Form Submission Notification]]"
  21.  
  22.   busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
  23.     attachment.filename = filename
  24.     const bufs = []
  25.     file.on("data", (data) => {
  26.       bufs.push(data)
  27.     })
  28.     file.on("end", () => {
  29.       attachment.content = Buffer.concat(bufs)
  30.     })
  31.     file.on("error", () => {
  32.       res.writeHead(500)
  33.       return res.end("INVALID FILE!!")
  34.     })
  35.   })
  36.   busboy.on("field", (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
  37.     if (fieldname === "ls-mail-subject") {
  38.       subject = val
  39.     } else {
  40.       fields[fieldname] = val
  41.     }
  42.   })
  43.   busboy.on("finish", async () => {
  44.     console.log("==> Done parsing form!")
  45.     try {
  46.       await mailer("form-submitted", {
  47.         to: process.env.RECEIVER_EMAILS,
  48.         subject,
  49.         locals: { fields },
  50.         attachments: (attachment.filename === "") ? [] : [attachment],
  51.         send: (process.env.NODE_ENV !== "development")
  52.       })
  53.     } catch (err) {
  54.       console.log("==> Email sending error: ", err)
  55.       res.writeHead(500)
  56.       return res.end("NOT OK!!")
  57.     }
  58.     res.writeHead(200)
  59.     return res.end("OK!!")
  60.   })
  61.   busboy.on("error", (err) => {
  62.     console.log("==> BusBoy error: ", err)
  63.     res.writeHead(500)
  64.     return res.end("OH NOES!!")
  65.   })
  66.   busboy.end(req.rawBody)
  67. }
  68.  
RAW Paste Data