Place the actual push subscription data into a push property on the subscription so that other properties can be added to it.
21 lines
834 B
TypeScript
21 lines
834 B
TypeScript
import { readSubscriptions, writeSubscriptions } from "~/server/database";
|
|
import { Subscription } from "~/shared/types/account";
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const body: { subscription: PushSubscriptionJSON } = await readBody(event);
|
|
const subscriptions = await readSubscriptions();
|
|
const existingIndex = subscriptions.findIndex(
|
|
sub => sub.type === "push" && sub.push.endpoint === body.subscription.endpoint
|
|
);
|
|
const subscription: Subscription = { type: "push", push: body.subscription };
|
|
if (existingIndex !== -1) {
|
|
subscriptions[existingIndex] = subscription;
|
|
} else {
|
|
subscriptions.push(subscription);
|
|
}
|
|
await writeSubscriptions(subscriptions);
|
|
if (existingIndex !== -1) {
|
|
return { message: "Existing subscription refreshed."};
|
|
}
|
|
return { message: "New subscription registered."};
|
|
})
|