Додані повідомлення та перепрацьована структура застосунку та api
This commit is contained in:
@@ -11,6 +11,44 @@ webpush.setVapidDetails(
|
||||
);
|
||||
|
||||
class Notification {
|
||||
async sendAll({ title, body, page }) {
|
||||
const sql = `
|
||||
SELECT * FROM subscription
|
||||
ORDER BY id
|
||||
`;
|
||||
|
||||
db.all(sql, async (err, rows) => {
|
||||
if (err) {
|
||||
console.error('DB error:', err.message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!rows.length) {
|
||||
console.log(`🐑 No subscriptions`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`📨 Sending notification to ${rows.length} subscriptions...`);
|
||||
|
||||
const payload = JSON.stringify({
|
||||
title: title ?? "Тестове повідомлення",
|
||||
body: body ?? "Ви успішно підписалися на отримання push повідомлень!",
|
||||
url: `https://${process.env.DOMAIN}${page ?? ""}`
|
||||
});
|
||||
|
||||
const results = await Promise.allSettled(rows.map(row => {
|
||||
const subscription = {
|
||||
endpoint: row.endpoint,
|
||||
keys: JSON.parse(row.keys),
|
||||
};
|
||||
return webpush.sendNotification(subscription, payload);
|
||||
}));
|
||||
|
||||
const failed = results.filter(r => r.status === 'rejected').length;
|
||||
console.log(`✅ Sent: ${rows.length - failed}, ❌ Failed: ${failed}`);
|
||||
});
|
||||
}
|
||||
|
||||
async sendSheep({ sheep_id, title, body, page }) {
|
||||
const sql = `
|
||||
SELECT * FROM subscription
|
||||
@@ -73,7 +111,7 @@ class Notification {
|
||||
}
|
||||
|
||||
if (!rows.length) {
|
||||
console.log(`🐑 No subscriptions found for sheep_id: ${sheep_id}`);
|
||||
console.log(`🐑 No subscriptions found for group_id: ${group_id}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -98,7 +136,7 @@ class Notification {
|
||||
});
|
||||
}
|
||||
|
||||
async sendStand({ title, body, page }) {
|
||||
async sendStandAdd({title, body, page }) {
|
||||
const sql = `
|
||||
SELECT
|
||||
subscription.*
|
||||
@@ -111,7 +149,7 @@ class Notification {
|
||||
possibilities
|
||||
ON possibilities.sheep_id = sheeps.id
|
||||
WHERE
|
||||
possibilities.can_view_stand = '1'
|
||||
possibilities.can_add_stand = '1'
|
||||
ORDER BY
|
||||
subscription.id;
|
||||
`;
|
||||
@@ -147,6 +185,22 @@ class Notification {
|
||||
console.log(`✅ Sent: ${rows.length - failed}, ❌ Failed: ${failed}`);
|
||||
});
|
||||
}
|
||||
|
||||
async sendEndpoint({ endpoint, keys, title, body, page }) {
|
||||
const payload = JSON.stringify({
|
||||
title: title ?? "Тестове повідомлення",
|
||||
body: body ?? "Ви успішно підписалися на отримання push повідомлень!",
|
||||
url: `https://${process.env.DOMAIN}${page ?? ""}`
|
||||
});
|
||||
|
||||
const subscription = {
|
||||
endpoint,
|
||||
keys: typeof keys === "string" ? JSON.parse(keys) : keys
|
||||
};
|
||||
|
||||
await webpush.sendNotification(subscription, payload);
|
||||
console.log("✅ Push sent");
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = new Notification();
|
||||
Reference in New Issue
Block a user