Last active
August 26, 2018 14:39
-
-
Save matitalatina/091ec918305b4e5578265429e69f888d to your computer and use it in GitHub Desktop.
Send webpush
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
function handleSubscription(subscription) { | |
const notificationPayload = { | |
notification: { | |
title: 'Blogial new post', | |
body: req.body.title, | |
icon: 'assets/icons/icon-512x512.png' | |
} | |
}; | |
return webpush.sendNotification( | |
subscription, | |
JSON.stringify(notificationPayload) | |
) | |
.catch(err => { | |
if (err.statusCode === 410) { | |
// Error is handled, it will not throw error 500 to user. | |
return Subscription.findOneAndRemove({ | |
_id: subscription._id | |
})(); | |
} else { | |
// Unknown error, it will throw error 500 to user. | |
throw err; | |
} | |
}); | |
} | |
exports.notification = (req, res, next) => { | |
const notificationPromises = Subscription.find() | |
.then(subscriptions => Promise.all(subscriptions.map(handleSubscription))); | |
notificationPromises | |
.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