owltide/server/database.ts

47 lines
1.4 KiB
TypeScript

import { readFile, writeFile } from "node:fs/promises";
import { Schedule } from "~/shared/types/schedule";
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"
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;
// Use the demo schedule if nothing is stored yet.
try {
schedule = generateDemoSchedule();
} catch (err) {
console.error(err);
throw err;
}
}
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");
}