2025-03-05 18:41:47 +01:00
|
|
|
import { readFile, writeFile } from "node:fs/promises";
|
|
|
|
import { Schedule } from "~/shared/types/schedule";
|
2025-03-05 22:15:46 +01:00
|
|
|
import { generateDemoSchedule } from "./generate-demo-schedule";
|
2025-03-05 18:41:47 +01:00
|
|
|
|
|
|
|
// 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.
|
|
|
|
|
2025-03-05 18:42:56 +01:00
|
|
|
const schedulePath = "data/schedule.json"
|
|
|
|
const subscriptionsPath = "data/subscriptions.json"
|
2025-03-05 18:41:47 +01:00
|
|
|
|
|
|
|
export async function readSchedule() {
|
|
|
|
let schedule: Schedule;
|
|
|
|
try {
|
|
|
|
schedule = JSON.parse(await readFile(schedulePath, "utf-8"));
|
|
|
|
} catch (err: any) {
|
|
|
|
if (err.code !== "ENOENT")
|
|
|
|
throw err;
|
2025-03-05 22:15:46 +01:00
|
|
|
// Use the demo schedule if nothing is stored yet.
|
|
|
|
try {
|
|
|
|
schedule = generateDemoSchedule();
|
|
|
|
} catch (err) {
|
|
|
|
console.error(err);
|
|
|
|
throw err;
|
2025-03-05 18:41:47 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return schedule;;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function writeSchedule(schedule: Schedule) {
|
|
|
|
await writeFile(schedulePath, JSON.stringify(schedule, undefined, "\t") + "\n", "utf-8");
|
|
|
|
}
|
|
|
|
|
|
|
|
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;;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function writeSubscriptions(subscriptions: PushSubscriptionJSON[]) {
|
|
|
|
await writeFile(subscriptionsPath, JSON.stringify(subscriptions, undefined, "\t") + "\n", "utf-8");
|
|
|
|
}
|