This repository has been archived by the owner on May 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hook.es6
64 lines (55 loc) · 1.72 KB
/
hook.es6
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
const webPush = require('web-push');
const Webtask = require('webtask-tools');
const app = new (require('express'))();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
webPush.setVapidDetails(
'mailto:[email protected]',
process.env.VAPID_PUBLIC,
process.env.VAPID_PRIVATE
);
app.post('/hook', (req, res) => {
const { storage } = req.webtaskContext;
storage.get((error, data) => {
if (error) { return res.send(400); }
if (!data) {
data = { subscriptions: [] }
}
const payload = JSON.stringify({
title: req.body[data.titleField] || 'Hook trigger',
body: req.body[data.bodyField] ||'New hook trigger',
});
const sendPushPromises = data.subscriptions
.map(data => {
webPush.sendNotification(data.sub, payload, { TTL: 3600 })
});
Promise.all(sendPushPromises)
.then(resp => res.json(resp))
.catch(e => res.send(400));
});
});
app.post('/subscribe', (req, res) => {
const { storage } = req.webtaskContext;
const { endpoint, keys } = req.body;
storage.get((errorGet, data) => {
if (errorGet) { return res.send(400); }
if (!data) {
data = { subscriptions: [] }
}
data.subscriptions.push({
titleField: false,
bodyField: false,
sub: {
endpoint,
keys: { p256dh: keys.p256dh, auth: keys.auth },
}
});
storage.set(data, function() {
return res.status(200).json({ ok: true })
});
})
});
module.exports = Webtask.fromExpress(app);