Push-notifications is fun

This commit is contained in:
Kasper Rynning-Tønnesen
2020-02-14 15:14:17 +01:00
parent eed8a84092
commit b8ca43abbf
2 changed files with 45 additions and 2 deletions

View File

@@ -27,7 +27,11 @@ webpush.setVapidDetails(
);
const sendNotification = (subscription, dataToSend = "") => {
webpush.sendNotification(subscription, dataToSend);
try {
webpush.sendNotification(subscription, dataToSend);
} catch (e) {
console.log("error", e);
}
};
router.use((req, res, next) => {
@@ -55,6 +59,19 @@ const saveToDatabase = async subscription => {
}
};
router.route("/send-notification").post(async (req, res) => {
if (!req.isAuthenticated()) {
res.send(false);
return;
}
const message = req.body.message;
let subs = await Subscription.find();
for (let i = 0; i < subs.length; i++) {
let subscription = subs[i]; //get subscription from your databse here.
sendNotification(subscription, message);
}
});
schedule.scheduleJob(
`0 50 ${lotteryConfig.hours - 1} * * ${lotteryConfig.date}`,
async () => {

View File

@@ -1,6 +1,15 @@
<template>
<div>
<h1>Registrering</h1>
<div class="notification-element">
<div class="label-div">
<label for="notification">Push-melding</label>
<input id="notification" type="text" v-model="pushMessage" />
</div>
</div>
<div class="button-container">
<button @click="sendPush">Send push</button>
</div>
<div class="color-container">
<div class="label-div">
<label for="blue">Blå</label>
@@ -119,7 +128,8 @@ export default {
yellow: 0,
payed: 0,
winners: [],
wines: []
wines: [],
pushMessage: ""
};
},
async mounted() {
@@ -141,6 +151,22 @@ export default {
}
},
methods: {
sendPush: async function() {
let _response = await fetch("/subscription/send-notification", {
headers: {
"Content-Type": "application/json"
// 'Content-Type': 'application/x-www-form-urlencoded',
},
method: "POST",
body: JSON.stringify({ message: this.pushMessage })
});
let response = await _response.json();
if (response) {
alert("Sendt!");
} else {
alert("Noe gikk galt!");
}
},
addWine: function(event) {
this.wines.push({
name: "",