-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
75 lines (67 loc) · 1.9 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
require('dotenv').load();
var Promise = require('es6-promise').Promise,
request = require('superagent'),
md5 = require('md5');
var API_URL = '.api.mailchimp.com/3.0/lists/',
DATACENTER = process.env.DATACENTER,
API_KEY = process.env.API_KEY,
LIST_ID = process.env.LIST_ID,
USERNAME = process.env.USERNAME,
STATUS = process.env.STATUS;
function urlForList() {
return 'https://' + DATACENTER + API_URL + LIST_ID + '/members/';
}
function urlForUser(emailAddress) {
return urlForList() + md5(emailAddress);
}
function updateSubscription(emailAddress) {
return new Promise(function(resolve, reject) {
request.patch(urlForUser(emailAddress))
.auth(USERNAME, API_KEY)
.send({ status: STATUS })
.end(function(err, res) {
if (err) {
console.log('ERROR', err);
reject({ status: err.status, message: err.response.text });
} else {
resolve(res.body);
}
});
});
}
function createSubscription(emailAddress) {
return new Promise(function(resolve, reject) {
request.post(urlForList())
.auth(USERNAME, API_KEY)
.send({ email_address: emailAddress, status: STATUS })
.end(function(err, res) {
if (err) {
console.log('ERROR', err);
reject({ status: err.status, message: err.response.text });
} else {
resolve(res.body);
}
});
});
}
exports.handler = function(event, context) {
var emailAddress = event.email;
function create() {
createSubscription(emailAddress)
.then(function(responseBody) {
context.succeed(responseBody);
})
.catch(function(err) {
context.fail(new Error(err));
});
}
updateSubscription(emailAddress)
.then(function(responseBody) {
context.succeed(responseBody);
})
.catch(function(err) {
if (err.status === 404) {
create();
}
});
};