Replace all async reads and writes to the JSON database with the sync reads and writes to prevent a data corruption race condition where two requests are processed at the same time and write to the same file, or one reads while the other writes causing read of partially written data.
42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
/*
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
*/
|
|
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 requireServerSessionWithUser(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 = 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);
|
|
}
|
|
writeSubscriptions(subscriptions);
|
|
if (existingIndex !== -1) {
|
|
return { message: "Existing subscription refreshed."};
|
|
}
|
|
return { message: "New subscription registered."};
|
|
})
|