v1.0.0
This commit is contained in:
70
api/services/push.service.js
Normal file
70
api/services/push.service.js
Normal file
@@ -0,0 +1,70 @@
|
||||
const crypto = require('crypto');
|
||||
const db = require("../config/db");
|
||||
const webpush = require('web-push');
|
||||
|
||||
const VAPID_PUBLIC_KEY = process.env.VAPID_PUBLIC_KEY;
|
||||
const VAPID_PRIVATE_KEY = process.env.VAPID_PRIVATE_KEY;
|
||||
|
||||
webpush.setVapidDetails(
|
||||
'mailto:rozenrod320@gmail.com',
|
||||
VAPID_PUBLIC_KEY,
|
||||
VAPID_PRIVATE_KEY
|
||||
);
|
||||
|
||||
class PushService {
|
||||
getKey() {
|
||||
return new Promise((res, rej) => {
|
||||
return res({ "publicKey": VAPID_PUBLIC_KEY });
|
||||
});
|
||||
}
|
||||
|
||||
createSubscribe(sheep_id, data) {
|
||||
return new Promise((res, rej) => {
|
||||
let sql = 'INSERT INTO subscription(sheep_id, endpoint, keys, device_name, device_model, created_at) VALUES (?, ?, ?, ?, ?, ?)';
|
||||
|
||||
db.run(sql, [
|
||||
Number(sheep_id),
|
||||
data.subscription.endpoint,
|
||||
JSON.stringify(data.subscription.keys),
|
||||
data.device?.name || "unknown",
|
||||
data.device?.model || "unknown",
|
||||
Math.floor(Date.now())
|
||||
], function (err) {
|
||||
if (err) {
|
||||
console.error(err.message);
|
||||
return res(false);
|
||||
} else {
|
||||
const payload = JSON.stringify(
|
||||
{
|
||||
"title": "Тестове повідомлення",
|
||||
"body": "Ви успішно підписалися на отримання push повідомлень!",
|
||||
"url": `https://${process.env.DOMAIN}`
|
||||
});
|
||||
|
||||
webpush.sendNotification(data.subscription, payload).catch(err => {
|
||||
console.error('Ошибка отправки:', err);
|
||||
})
|
||||
|
||||
return res({ "status": "ok" });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
deleteSubscribe(data) {
|
||||
return new Promise((res, rej) => {
|
||||
db.run('DELETE FROM subscription WHERE endpoint = ?', [data.endpoint], function (err) {
|
||||
if (err) {
|
||||
console.error(err.message);
|
||||
return res(false);
|
||||
} else if (this.changes === 0) {
|
||||
return res(false);
|
||||
} else {
|
||||
res({ "status": "ok" });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new PushService();
|
||||
Reference in New Issue
Block a user