-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.js
59 lines (52 loc) · 1.59 KB
/
handler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
require("dotenv").config();
const jwt = require("jsonwebtoken");
const nodemailer = require("nodemailer");
const nodemailerSendgrid = require("nodemailer-sendgrid");
module.exports.notifier = (event, context, callback) => {
let verifiedEvent;
try {
verifiedEvent = jwt.verify(JSON.parse(event.body).payload, process.env.JWT_SECRET);
} catch (e) {
return sendResponse({ statusCode: 401, callback, body: e });
}
sendEmail(verifiedEvent)
.then(info => {
sendResponse({ statusCode: 200, body: info, callback });
})
.catch(error => {
return sendResponse({ statusCode: 422, body: error, callback });
});
};
const sendResponse = ({ statusCode, body, callback }) => {
const response = {
statusCode,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
},
multiValueHeaders: {
"Access-Control-Allow-Headers": ["Access-Control-Allow-Origin", "Content-Type"],
},
body: JSON.stringify(body),
};
return callback(null, response);
};
const _smtpConnect = () => {
return new Promise(resolve => {
const transporter = nodemailer.createTransport(nodemailerSendgrid({ apiKey: process.env.API_KEY }));
resolve(transporter);
});
};
const sendEmail = payload => {
return _smtpConnect().then(transporter => {
return new Promise((resolve, reject) => {
const mailOptions = { ...payload, text: payload.body, html: payload.body };
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
reject(error);
}
resolve(info);
});
});
});
};