-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
90 lines (78 loc) · 2.03 KB
/
app.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
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
'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, welcomeTemplateID) {
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: welcomeTemplateID
};
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);
// cb(null, response);
}).catch(error => reject(error));
});
}
module.exports = (context, cb) => {
console.log(JSON.stringify(context));
const email = context.body.email;
const firstName = context.body.first_name;
const welcomeEmail = context.query.welcome_email;
client.setApiKey(context.secrets.SENDGRID_API_KEY);
addSendgridRecipient(client, email, firstName)
.then((response) => {
if (welcomeEmail === "true" || welcomeEmail === "1") {
const senderEmail = context.secrets.SENDGRID_WELCOME_SENDER_EMAIL;
const senderName = context.secrets.SENDGRID_WELCOME_SENDER_NAME;
const welcomeTemplateID = context.secrets.SENDGRID_WELCOME_TEMPLATE_ID;
sendWelcomeEmail(client, email, firstName, senderEmail, senderName, welcomeTemplateID)
.then( response => cb(null, response))
.catch(cb);
} else {
cb(null, response);
}
})
.catch(cb);
};