/
index.js
96 lines (82 loc) 路 2.74 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import dotenv from 'dotenv';
import fetch from 'node-fetch';
import Fastify from 'fastify';
import cron from 'node-cron';
dotenv.config();
const fastify = Fastify({
logger: true
})
const sendyDefaults = {
api_key: process.env.SENDY_API_KEY,
list: process.env.SENDY_LIST
}
fastify.get('/', function(request, reply) {
reply.send({welcome:'You found my hidden project 馃く'});
})
fastify.post('/sendy-webhook', async function (request, reply) {
const data = request.body;
if (!data.trigger || !data.email) {
throw new Error('Invalid data')
}
const {trigger, email} = data;
if (['subscribe', 'unsubscribe'].includes(trigger)) {
const url = `subscribers${trigger === 'unsubscribe' ? '/unsubscribe' : ''}`;
const status = await callRevueAPI(url, 'POST', convertToFormData({email}))
return reply.send(status);
}
throw new Error('Trigger not found')
})
fastify.listen({port: process.env.PORT || 3000, host: '0.0.0.0'}, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})
const callRevueAPI = async (endpoint, method = 'GET', body) => {
const response = await fetch(`https://www.getrevue.co/api/v2/${endpoint}`, {
headers: {
Authorization: `Token ${process.env.REVUE_API_TOKEN}`,
'Content-Type': body ? 'application/x-www-form-urlencoded' : 'application/json',
},
method,
body,
}).then((res) => res.json());
return response;
}
const callSendyAPI = async (endpoint, body) => {
const response = await fetch(`https://sendy.daily-dev-tips.com/${endpoint}`, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
method: 'POST',
body
}).then((res) => res.status);
return response;
}
const convertToFormData = (data) => {
const formData = new URLSearchParams();
Object.keys(data).forEach((key) => {
formData.set(key, data[key]);
});
return formData;
}
cron.schedule('0 2 * * *', async () => {
const revueUnsubscribed = await callRevueAPI('subscribers/unsubscribed');
for (const unsubscriber of revueUnsubscribed) {
const unsubscribeSendy = await callSendyAPI('/unsubscribe', convertToFormData({
...sendyDefaults,
email: unsubscriber.email
}))
console.log(unsubscribeSendy);
}
const revueSubscribed = await callRevueAPI('subscribers');
for (const subscriber of revueSubscribed) {
const subscribeSendy = await callSendyAPI('/subscribe', convertToFormData({
...sendyDefaults,
email: subscriber.email,
silent: true,
}))
console.log(subscribeSendy);
}
console.log('all done');
});