Last active
December 28, 2020 22:29
-
-
Save smpnjn/9d03287b26dfeda61cba74e39d29279b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Service Worker Notifications | |
| const publicVapidKey = '<<<Public Vapid Key>>>'; | |
| const privateVapidKey = '<<<Private Vapid Key>>>'; | |
| webpush.setVapidDetails('mailto:someEmail@emailSite.com', publicVapidKey, privateVapidKey); | |
| app.post('/subscribe', jsonParser, async function(req, res) { | |
| try { | |
| let hash = objectHash(req.body); | |
| let subscription = req.body; | |
| let checkSubscription = await Subscription.Subscription.find({ 'hash' : hash }); | |
| let theMessage = JSON.stringify({ title: 'You have already subscribed', body: 'Some body text here.' }); | |
| if(checkSubscription.length == 0) { | |
| const newSubscription = new Subscription.Subscription({ | |
| hash: hash, | |
| subscriptionEl: subscription | |
| }); | |
| newSubscription.save(function (err) { | |
| if (err) { | |
| theMessage = JSON.stringify({ title: 'We ran into an error', body: 'Please try again later' }); | |
| webpush.sendNotification(subscription, payload).catch(error => { | |
| console.error(error.stack); | |
| }); | |
| res.status(400); | |
| } else { | |
| theMessage = JSON.stringify({ title: 'Thank you for Subscribing!', body: 'Some body text here' }); | |
| webpush.sendNotification(subscription, payload).catch(error => { | |
| console.error(error.stack); | |
| }); | |
| res.status(201); | |
| } | |
| }); | |
| } else { | |
| webpush.sendNotification(subscription, theMessage).catch(error => { | |
| console.error(error.stack); | |
| }); | |
| res.status(400); | |
| } | |
| } catch(e) { | |
| console.log(e); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment