-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (73 loc) · 1.98 KB
/
index.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
const request = require('request');
require('dotenv').config();
//Sendy subscription function
function subscribe(name, email) {
return new Promise(function(resolve, reject) {
var result = '';
const options = {
url: process.env.SENDY_HOST + "/subscribe",
method: "POST",
headers: {
"Content-Type": "multipart/form-data"
},
formData: {
"api_key": process.env.SENDY_API_KEY,
"name": name,
"email": email,
"list": process.env.SENDY_LIST
}
}
request(options, function (err, res, body) {
if(err) console.log(err);
resolve(body);
});
});
}
//Sendy unsubscribe function
function unsubscribe(email) {
return new Promise(function(resolve, reject) {
var result = '';
const options = {
url: process.env.SENDY_HOST + "/unsubscribe",
method: "POST",
headers: {
"Content-Type": "multipart/form-data"
},
formData: {
"email": email,
"list": process.env.SENDY_LIST
}
}
request(options, function (err, res, body) {
if(err) console.log(err);
resolve(body);
});
});
}
module.exports.handler = async (event) => {
var data = '';
var eventType = event.headers["X-Discourse-Event-Type"];
if (eventType == "ping") {
data = 'A ping was received from Discourse';
}
else if (eventType == "user" && event.headers["X-Discourse-Event"] == "user_created") {
var validJSON = JSON.parse(event.body);
data = await subscribe(validJSON.user.name, validJSON.user.email);
}
else if (eventType == "user" && event.headers["X-Discourse-Event"] == "user_destroyed") {
var validJSON = JSON.parse(event.body);
data = await unsubscribe(validJSON.user.email);
}
else data = "No preference set for this event type";
return sendRes(200, data);
};
const sendRes = (status, body) => {
var response = {
statusCode: status,
headers: {
"Content-Type": "text/html"
},
body: body
};
return response;
};