-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
54 lines (44 loc) · 1.73 KB
/
index.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
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const webpush = require('web-push')
const app = express()
app.use(cors())
app.use(bodyParser.json())
const port = 4000
app.get('/', (req, res) => res.send('Hello World'))
const dummyDb = { subscription: null } //dummy in memory store
const saveToDatabase = async subscription => {
// Since this is a demo app, I am going to save this in a dummy in memory store. Do not do this in your apps.
// Here you should be writing your db logic to save it.
dummyDb.subscription = subscription
}
// The new /save-subscription endpoint
app.post('/save-subscription', async (req, res) => {
const subscription = req.body
await saveToDatabase(subscription) //Method to save the subscription to Database
res.json({ message: 'success' })
})
const vapidKeys = {
publicKey: 'BPXi5ocqGCdMnF3QEWCJwBkYezEi-j8qUCJoVp53dn8O3N11fRHEz8Q9BcomKyh97kg4i1j5TZrbwdDiAHqvYFA',
privateKey: 'NdxxkTYfyI2uHES7mj4arBPsyqUbsluYtZOGEKoyqIA'
}
//setting our previously generated VAPID keys
webpush.setVapidDetails(
'mailto:[email protected]',
vapidKeys.publicKey,
vapidKeys.privateKey
)
//function to send the notification to the subscribed device
const sendNotification = (subscription, dataToSend='') => {
webpush.sendNotification(subscription, dataToSend)
}
//route to test send notification
app.get('/send-notification', (req, res) => {
const subscription = dummyDb.subscription //get subscription from your databse here.
console.log(subscription)
const message = '瓜叔下午好!'
sendNotification(subscription, message)
res.json({ message: 'message sent' })
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))