This repository has been archived by the owner on Nov 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 336
/
server.js
51 lines (46 loc) · 1.55 KB
/
server.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
// Use the web-push library to hide the implementation details of the communication
// between the application server and the push service.
// For details, see https://tools.ietf.org/html/draft-ietf-webpush-protocol and
// https://tools.ietf.org/html/draft-ietf-webpush-encryption.
const webPush = require("web-push");
if (!process.env.VAPID_PUBLIC_KEY || !process.env.VAPID_PRIVATE_KEY) {
console.log(
"You must set the VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY " +
"environment variables. You can use the following ones:"
);
console.log(webPush.generateVAPIDKeys());
return;
}
// Set the keys used for encrypting the push messages.
webPush.setVapidDetails(
"https://example.com/",
process.env.VAPID_PUBLIC_KEY,
process.env.VAPID_PRIVATE_KEY
);
module.exports = function (app, route) {
app.get(route + "vapidPublicKey", function (req, res) {
res.send(process.env.VAPID_PUBLIC_KEY);
});
app.post(route + "register", function (req, res) {
// A real world application would store the subscription info.
res.sendStatus(201);
});
app.post(route + "sendNotification", function (req, res) {
const subscription = req.body.subscription;
const payload = req.body.payload;
const options = {
TTL: req.body.ttl,
};
setTimeout(function () {
webPush
.sendNotification(subscription, payload, options)
.then(function () {
res.sendStatus(201);
})
.catch(function (error) {
console.log(error);
res.sendStatus(500);
});
}, req.body.delay * 1000);
});
};