Rename and refactor the types passed over the API to be based on an entity that's either living or a tombstone. A living entity has a deleted property that's either undefined or false, while a tombstone has a deleted property set to true. All entities have a numeric id and an updatedAt timestamp. To sync entities, an array of replacements are passed around. Living entities are replaced with tombstones when they're deleted. And tombstones are replaced with living entities when restored.
38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
import { readSubscriptions, writeSubscriptions } from "~/server/database";
|
|
import { type ApiSubscription, apiSubscriptionSchema } from "~/shared/types/api";
|
|
import { z } from "zod/v4-mini";
|
|
|
|
const subscriptionSchema = z.strictObject({
|
|
subscription: apiSubscriptionSchema.def.shape.push,
|
|
});
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const session = await requireServerSession(event);
|
|
const { success, error, data: body } = subscriptionSchema.safeParse(await readBody(event));
|
|
if (!success) {
|
|
throw createError({
|
|
status: 400,
|
|
statusText: "Bad Request",
|
|
message: z.prettifyError(error),
|
|
});
|
|
}
|
|
const subscriptions = await readSubscriptions();
|
|
const existingIndex = subscriptions.findIndex(
|
|
sub => sub.type === "push" && sub.sessionId === session.id
|
|
);
|
|
const subscription: ApiSubscription = {
|
|
type: "push",
|
|
sessionId: session.id,
|
|
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."};
|
|
})
|