Refactor code saving data
Move the code dealing with saving and loading data to server/database to gather it all up into one place.
This commit is contained in:
parent
754d175ce2
commit
6ea3567c94
8 changed files with 64 additions and 58 deletions
|
@ -1,5 +1,5 @@
|
|||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import webPush from "web-push";
|
||||
import { readSubscriptions, writeSubscriptions } from "~/server/database";
|
||||
|
||||
webPush.setVapidDetails(
|
||||
"mailto:webmaster@hornwitser.no",
|
||||
|
@ -9,16 +9,7 @@ webPush.setVapidDetails(
|
|||
|
||||
export async function sendPush(title: string, body: string) {
|
||||
const payload = JSON.stringify({ title, body });
|
||||
let subscriptions: PushSubscriptionJSON[];
|
||||
try {
|
||||
subscriptions = JSON.parse(await readFile("push-subscriptions.json", "utf-8"));
|
||||
} catch (err: any) {
|
||||
if (err.code !== "ENOENT") {
|
||||
console.log(`Dropping "${payload}", no push subscribers`);
|
||||
return;
|
||||
}
|
||||
subscriptions = [];
|
||||
}
|
||||
const subscriptions = await readSubscriptions();
|
||||
console.log(`Sending "${payload}" to ${subscriptions.length} subscribers`);
|
||||
const removeIndexes = [];
|
||||
for (let index = 0; index < subscriptions.length; index += 1) {
|
||||
|
@ -46,11 +37,7 @@ export async function sendPush(title: string, body: string) {
|
|||
for (const index of removeIndexes) {
|
||||
subscriptions.splice(index, 1);
|
||||
}
|
||||
await writeFile(
|
||||
"push-subscriptions.json",
|
||||
JSON.stringify(subscriptions, undefined, "\t"),
|
||||
"utf-8"
|
||||
);
|
||||
await writeSubscriptions(subscriptions);
|
||||
}
|
||||
console.log("Push notices sent");
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue