-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
104 lines (97 loc) · 2.46 KB
/
app.js
File metadata and controls
104 lines (97 loc) · 2.46 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"use latest";
const client = require("@sendgrid/client");
function addSendgridRecipient(client, email, firstName) {
return new Promise((fulfill, reject) => {
const data = [
{
email: email,
first_name: firstName
}
];
const request = {
method: "POST",
url: "/v3/contactdb/recipients",
body: data
};
client
.request(request)
.then(([response, body]) => {
console.log(response.statusCode);
console.log(body);
fulfill(response);
// cb(null, response);
})
.catch(error => reject(error));
});
}
function sendWelcomeEmail(client, email, firstName, senderEmail, senderName, templateID) {
return new Promise((fulfill, reject) => {
const data = {
from: {
email: senderEmail,
name: senderName
},
reply_to: {
email: senderEmail
},
personalizations: [
{
to: [
{
email: email,
name: firstName
}
],
substitutions: {
"<%name%>": firstName
}
}
],
template_id: templateID
};
const request = {
method: "POST",
url: "/v3/mail/send",
body: data
};
client
.request(request)
.then(([response, body]) => {
console.log(response.statusCode);
console.log(body);
fulfill(response);
})
.catch(error => reject(error));
});
}
exports.handler = function(event, context, callback) {
const {
SENDGRID_API_KEY,
SENDGRID_WELCOME_SENDER_EMAIL,
SENDGRID_WELCOME_SENDER_NAME,
SENDGRID_WELCOME_TEMPLATE_ID
} = process.env;
const body = JSON.parse(event.body);
const email = body.email;
const firstName = body.first_name;
const welcomeEmail = event.queryStringParameters.welcome_email === "true";
client.setApiKey(SENDGRID_API_KEY);
addSendgridRecipient(client, email, firstName)
.then((response, body) => {
if (welcomeEmail) {
sendWelcomeEmail(
client,
email,
firstName,
SENDGRID_WELCOME_SENDER_EMAIL,
SENDGRID_WELCOME_SENDER_NAME,
SENDGRID_WELCOME_TEMPLATE_ID
)
.then(response => callback(null, { statusCode: response.statusCode, body: "" }) )
.catch(err => callback(err, null));
} else {
callback(null, { statusCode: response.statusCode, body: "" });
}
})
.catch(err => callback(err, null));
};