27 lines
867 B
TypeScript
27 lines
867 B
TypeScript
|
import { readFile, writeFile } from "fs/promises";
|
||
|
|
||
|
export async function POST(request: Request) {
|
||
|
const body: { subscription: PushSubscriptionJSON } = await request.json();
|
||
|
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.splice(existingIndex, 1);
|
||
|
} else {
|
||
|
return new Response(JSON.stringify({ message: "No subscription registered."}));
|
||
|
}
|
||
|
await writeFile(
|
||
|
"push-subscriptions.json",
|
||
|
JSON.stringify(subscriptions, undefined, "\t"),
|
||
|
"utf-8"
|
||
|
);
|
||
|
return new Response(JSON.stringify({ message: "Existing subscription removed."}));
|
||
|
}
|