2025-03-05 15:36:50 +01:00
|
|
|
import { readFile, writeFile } from "node:fs/promises";
|
2025-02-28 15:32:03 +01:00
|
|
|
|
2025-03-05 15:36:50 +01:00
|
|
|
export default defineEventHandler(async (event) => {
|
|
|
|
const body: { subscription: PushSubscriptionJSON } = await readBody(event);
|
2025-02-28 15:32:03 +01:00
|
|
|
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 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"
|
|
|
|
);
|
|
|
|
if (existingIndex !== -1) {
|
2025-03-05 15:36:50 +01:00
|
|
|
return { message: "Existing subscription refreshed."};
|
2025-02-28 15:32:03 +01:00
|
|
|
}
|
2025-03-05 15:36:50 +01:00
|
|
|
return { message: "New subscription registered."};
|
|
|
|
})
|