Skip to content

Instantly share code, notes, and snippets.

@matitalatina
Last active August 26, 2018 14:39
Show Gist options
  • Save matitalatina/091ec918305b4e5578265429e69f888d to your computer and use it in GitHub Desktop.
Save matitalatina/091ec918305b4e5578265429e69f888d to your computer and use it in GitHub Desktop.
Send webpush
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