This repository has been archived by the owner on Sep 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
serve-push.js
74 lines (61 loc) · 2.06 KB
/
serve-push.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
const express = require('express');
const bodyParser = require('body-parser');
const configuredWebPush = require('./configured-web-push');
const { Subscription } = require('./db');
const router = express.Router();
router.use(bodyParser.json());
// Push Logic
router.get('/api/key', function(req, res) {
if (configuredWebPush.vapidPublicKey !== '') {
res.send({
key: configuredWebPush.vapidPublicKey
});
} else {
res.status(500).send({
key: 'VAPID KEYS ARE NOT SET'
});
}
});
router.post('/api/subscribe', async function(req, res) {
try {
const sub = req.body.subscription;
// Find if user is already subscribed searching by `endpoint`
const exists = await Subscription.findOne({ endpoint: sub.endpoint });
if (exists) {
res.status(400).send('Subscription already exists');
return;
}
await (new Subscription(sub)).save();
res.status(200).send('Success');
} catch (e) {
res.status(500).send(e.message);
}
});
router.post('/api/unsubscribe', async function(req, res) {
try {
const sub = req.body.subscription;
await Subscription.remove({endpoint: sub.endpoint});
console.log('Deleted: ' + sub.endpoint);
res.status(200).send('Success');
} catch (e) {
res.status(500).send(e.message);
}
});
router.post('/api/notify', async function(req, res) {
try {
const data = req.body;
await configuredWebPush.webPush.sendNotification(data.subscription, data.payload, { contentEncoding: data.encoding })
.then(function (response) {
console.log('Response: ' + JSON.stringify(response, null, 4));
res.status(201).send(response);
})
.catch(function (e) {
console.log('Error: ' + JSON.stringify(e, null, 4));
res.status(201).send(e);
});
} catch (e) {
res.status(500)
.send(e.message);
}
});
module.exports = router;