-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubscriptionHandler.js
49 lines (42 loc) · 1.5 KB
/
subscriptionHandler.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
const subscriptions = {};
var crypto = require("crypto");
const webpush = require("web-push");
const vapidKeys = {
privateKey: "bdSiNzUhUP6piAxLH-tW88zfBlWWveIx0dAsDO66aVU",
publicKey: "BIN2Jc5Vmkmy-S3AUrcMlpKxJpLeVRAfu9WBqUbJ70SJOCWGCGXKY-Xzyh7HDr6KbRDGYHjqZ06OcS3BjD7uAm8"
};
webpush.setVapidDetails("mailto:[email protected]", vapidKeys.publicKey, vapidKeys.privateKey);
function createHash(input) {
const md5sum = crypto.createHash("md5");
md5sum.update(Buffer.from(input));
return md5sum.digest("hex");
}
function handlePushNotificationSubscription(req, res) {
const subscriptionRequest = req.body.subscrition;
console.log(subscriptionRequest)
const susbscriptionId = req.body.user_id;
console.log(susbscriptionId)
subscriptions[susbscriptionId] = subscriptionRequest;
console.log(subscriptions)
res.status(201).json({ id: susbscriptionId });
}
function sendPushNotification(req, res) {
const subscriptionId = req.params.id;
const pushSubscription = subscriptions[subscriptionId];
webpush
.sendNotification(
pushSubscription,
JSON.stringify({
title: "New Product Available ",
text: "HEY! Take a look at this brand new t-shirt!",
image: "/images/jason-leung-HM6TMmevbZQ-unsplash.jpg",
tag: "new-product",
url: "/new-product-jason-leung-HM6TMmevbZQ-unsplash.html"
})
)
.catch(err => {
console.log(err);
});
res.status(202).json({});
}
module.exports = { handlePushNotificationSubscription, sendPushNotification };