2025-03-05 18:41:47 +01:00
|
|
|
import { readSubscriptions, writeSubscriptions } from "~/server/database";
|
2025-03-07 12:30:39 +01:00
|
|
|
import { Subscription } from "~/shared/types/account";
|
2025-02-28 15:32:03 +01:00
|
|
|
|
2025-03-05 15:36:50 +01:00
|
|
|
export default defineEventHandler(async (event) => {
|
2025-03-07 14:11:07 +01:00
|
|
|
const session = await requireAccountSession(event);
|
2025-03-05 15:36:50 +01:00
|
|
|
const body: { subscription: PushSubscriptionJSON } = await readBody(event);
|
2025-03-05 18:41:47 +01:00
|
|
|
const subscriptions = await readSubscriptions();
|
2025-03-07 12:30:39 +01:00
|
|
|
const existingIndex = subscriptions.findIndex(
|
2025-03-07 14:11:07 +01:00
|
|
|
sub => sub.type === "push" && sub.sessionId === session.id
|
2025-03-07 12:30:39 +01:00
|
|
|
);
|
2025-03-07 14:11:07 +01:00
|
|
|
const subscription: Subscription = {
|
|
|
|
type: "push",
|
|
|
|
sessionId: session.id,
|
|
|
|
push: body.subscription
|
|
|
|
};
|
2025-02-28 15:32:03 +01:00
|
|
|
if (existingIndex !== -1) {
|
2025-03-07 12:30:39 +01:00
|
|
|
subscriptions[existingIndex] = subscription;
|
2025-02-28 15:32:03 +01:00
|
|
|
} else {
|
2025-03-07 12:30:39 +01:00
|
|
|
subscriptions.push(subscription);
|
2025-02-28 15:32:03 +01:00
|
|
|
}
|
2025-03-05 18:41:47 +01:00
|
|
|
await writeSubscriptions(subscriptions);
|
2025-02-28 15:32:03 +01:00
|
|
|
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."};
|
|
|
|
})
|