Pull JSON read file logic into a function

This commit is contained in:
Hornwitser 2025-03-07 12:25:10 +01:00
parent 8da4b02154
commit b4934005ae

View file

@ -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 // 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. // this into proper application this should be replaced with an actual database.
const schedulePath = "data/schedule.json" const schedulePath = "data/schedule.json";
const subscriptionsPath = "data/subscriptions.json" const subscriptionsPath = "data/subscriptions.json";
export async function readSchedule() { async function readJson<T>(filePath: string, fallback: T) {
let schedule: Schedule; let data: T extends () => infer R ? R : T;
try { try {
schedule = JSON.parse(await readFile(schedulePath, "utf-8")); data = JSON.parse(await readFile(filePath, "utf-8"));
} catch (err: any) { } catch (err: any) {
if (err.code !== "ENOENT") if (err.code !== "ENOENT")
throw err; throw err;
// Use the demo schedule if nothing is stored yet. data = typeof fallback === "function" ? fallback() : fallback;
try {
schedule = generateDemoSchedule();
} catch (err) {
console.error(err);
throw err;
} }
} return data;
return schedule;; }
export async function readSchedule() {
return readJson(schedulePath, generateDemoSchedule);
} }
export async function writeSchedule(schedule: Schedule) { export async function writeSchedule(schedule: Schedule) {
@ -31,15 +29,8 @@ export async function writeSchedule(schedule: Schedule) {
} }
export async function readSubscriptions() { export async function readSubscriptions() {
let subscriptions: PushSubscriptionJSON[]; let subscriptions = await readJson<PushSubscriptionJSON[]>(subscriptionsPath, []);
try { return subscriptions;
subscriptions = JSON.parse(await readFile(subscriptionsPath, "utf-8"));
} catch (err: any) {
if (err.code !== "ENOENT")
throw err;
subscriptions = [];
}
return subscriptions;;
} }
export async function writeSubscriptions(subscriptions: PushSubscriptionJSON[]) { export async function writeSubscriptions(subscriptions: PushSubscriptionJSON[]) {