Last active
August 26, 2018 11:46
-
-
Save whisher/349e97641ef08d3a1773381ec994e843 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
| const triggerPushMsg = function(subscription, dataToSend) { | |
| let _subscription = subscription.subscriber; | |
| let pushSubscription = JSON.parse(_subscription); | |
| let buildPushSubscription = { | |
| endpoint: pushSubscription.endpoint, | |
| keys: pushSubscription.keys | |
| }; | |
| return webpush.sendNotification(buildPushSubscription, dataToSend) | |
| .catch((err) => { | |
| if (err.statusCode === 410) { | |
| return Subscription.findOneAndRemove({ _id: subscription._id})(); | |
| } else { | |
| console.log('Subscription is no longer valid: ', err); | |
| } | |
| }); | |
| }; | |
| exports.notification = (req, res, next) => { | |
| const notificationPayload = { | |
| notification: { | |
| title: 'Blogial new post', | |
| body: req.body.title, | |
| icon: 'assets/icons/icon-512x512.png' | |
| } | |
| }; | |
| Subscription.find() | |
| .then((subscriptions) => { | |
| let promiseChain = Promise.resolve(); | |
| for (let i = 0; i < subscriptions.length; i++) { | |
| let subscription = subscriptions[i]; | |
| promiseChain = promiseChain.then(() => { | |
| return triggerPushMsg(subscription, notificationPayload); | |
| }); | |
| } | |
| return promiseChain; | |
| }) | |
| .then((response) => { | |
| res.status(200).json(response); | |
| }) | |
| .catch(error => { | |
| res.status(500).json(error); | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment