diff --git a/server/database.ts b/server/database.ts index 3133c9c..7ba2438 100644 --- a/server/database.ts +++ b/server/database.ts @@ -5,25 +5,23 @@ import { generateDemoSchedule } from "./generate-demo-schedule"; // For this demo I'm just storing the runtime data in JSON files. When making // this into proper application this should be replaced with an actual database. -const schedulePath = "data/schedule.json" -const subscriptionsPath = "data/subscriptions.json" +const schedulePath = "data/schedule.json"; +const subscriptionsPath = "data/subscriptions.json"; -export async function readSchedule() { - let schedule: Schedule; +async function readJson(filePath: string, fallback: T) { + let data: T extends () => infer R ? R : T; try { - schedule = JSON.parse(await readFile(schedulePath, "utf-8")); + data = JSON.parse(await readFile(filePath, "utf-8")); } catch (err: any) { if (err.code !== "ENOENT") throw err; - // Use the demo schedule if nothing is stored yet. - try { - schedule = generateDemoSchedule(); - } catch (err) { - console.error(err); - throw err; - } + data = typeof fallback === "function" ? fallback() : fallback; } - return schedule;; + return data; +} + +export async function readSchedule() { + return readJson(schedulePath, generateDemoSchedule); } export async function writeSchedule(schedule: Schedule) { @@ -31,15 +29,8 @@ export async function writeSchedule(schedule: Schedule) { } export async function readSubscriptions() { - let subscriptions: PushSubscriptionJSON[]; - try { - subscriptions = JSON.parse(await readFile(subscriptionsPath, "utf-8")); - } catch (err: any) { - if (err.code !== "ENOENT") - throw err; - subscriptions = []; - } - return subscriptions;; + let subscriptions = await readJson(subscriptionsPath, []); + return subscriptions; } export async function writeSubscriptions(subscriptions: PushSubscriptionJSON[]) {