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,27 +1,15 @@
|
|||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { readSubscriptions, writeSubscriptions } from "~/server/database";
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body: { subscription: PushSubscriptionJSON } = await readBody(event);
|
||||
let subscriptions: PushSubscriptionJSON[];
|
||||
try {
|
||||
subscriptions = JSON.parse(await readFile("push-subscriptions.json", "utf-8"));
|
||||
} catch (err: any) {
|
||||
if (err.code !== "ENOENT") {
|
||||
throw err;
|
||||
}
|
||||
subscriptions = [];
|
||||
}
|
||||
const subscriptions = await readSubscriptions();
|
||||
const existingIndex = subscriptions.findIndex(sub => sub.endpoint === body.subscription.endpoint);
|
||||
if (existingIndex !== -1) {
|
||||
subscriptions[existingIndex] = body.subscription;
|
||||
} else {
|
||||
subscriptions.push(body.subscription);
|
||||
}
|
||||
await writeFile(
|
||||
"push-subscriptions.json",
|
||||
JSON.stringify(subscriptions, undefined, "\t"),
|
||||
"utf-8"
|
||||
);
|
||||
await writeSubscriptions(subscriptions);
|
||||
if (existingIndex !== -1) {
|
||||
return { message: "Existing subscription refreshed."};
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue