-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathwebpush.js
More file actions
32 lines (25 loc) · 1.11 KB
/
webpush.js
File metadata and controls
32 lines (25 loc) · 1.11 KB
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
'use strict'
let webPush
let vapidKeys
const setup = (options = global.CONFIG) => {
const { WEBPUSH_VAPID_URL } = options || {}
if (!webPush) {
webPush = require('web-push')
// We use webpush to generate our public and private keys
vapidKeys = webPush.generateVAPIDKeys()
const { publicKey, privateKey } = vapidKeys
// We are giving webpush the required information to encrypt our data
webPush.setVapidDetails(WEBPUSH_VAPID_URL, publicKey, privateKey)
}
}
// This function takes a subscription object and a payload as an argument. It will try to encrypt the payload
// then attempt to send a notification via the subscription's endpoint
const send = async (subscription, payload, TTL=60) => {
// This means we won't resend a notification if the client is offline
const options = { TTL } // what if TTL = 0 ?
// web-push's sendNotification function does all the work for us
if (!subscription.keys) { payload = payload || null }
return await webPush.sendNotification(subscription, payload, options)
}
const getPubKey = () => vapidKeys.publicKey
module.exports = { getPubKey, send, setup }