forked from cloudinary-training/cld-webhooks
/
webhook_notify_email.js
70 lines (64 loc) · 2.13 KB
/
webhook_notify_email.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
require('dotenv').config();
const sgMail = require('@sendgrid/mail');
// set up an async function to server as handler
exports.handler = async function (event, context) {
// fail if not a POST
if (!event.body || event.httpMethod !== 'POST') {
return {
statusCode: 400,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
},
body: JSON.stringify({
status: 'invalid-method',
}),
};
}
// get data from POST
const data = JSON.parse(event.body);
// console.log(JSON.stringify(data, null, 2));
console.log(`header info: ${JSON.stringify(event.headers,null,2)}`);
// register the SendGrid API KEY
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
// set up a SendGrid message
// the TO_RECIPIENTS variable contains 1 or more email addresses separated by space
// for example "bob@abc.com sally@abc.com"
// the FROM_VERIFIED_SENDER is the email address registered with SEND_GRID
// we're forwarding the Cloudinary response data and it contains URL
// disable clickTracking so that URLs are passed as received here
const msg = {
to: process.env.TO_RECIPIENTS.split(' '),
from: process.env.FROM_VERIFIED_SENDER,
subject: 'Webhook Notification',
text: JSON.stringify(data, null, 2),
trackingSettings: {
clickTracking: {
enable: false
}
}
};
// log the message
console.log('msg', msg);
try {
// call SendGrid and log response if needed
const response = await sgMail.sendMultiple(msg);
// console.log('success', response[0].statusCode);
// console.log('success-response',response[0]);
// send success message
return {
statusCode: response[0].statusCode,
body: JSON.stringify({ message: response[0] }),
};
} catch (error) {
// log error if needed and send error response
// console.error('error', JSON.stringify(error, 0, 2));
// const errorMsg = error.response.body.errors[0].message;
// console.log(errorMsg);
// send fail message
return {
statusCode: error.code,
body: error.response.body.errors[0].message,
};
}
};