Place the actual push subscription data into a push property on the subscription so that other properties can be added to it.
43 lines
1.4 KiB
TypeScript
43 lines
1.4 KiB
TypeScript
import { readFile, writeFile } from "node:fs/promises";
|
|
import { Schedule } from "~/shared/types/schedule";
|
|
import { generateDemoSchedule } from "./generate-demo-schedule";
|
|
import { Subscription } from "~/shared/types/account";
|
|
|
|
// 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";
|
|
|
|
async function readJson<T>(filePath: string, fallback: T) {
|
|
let data: T extends () => infer R ? R : T;
|
|
try {
|
|
data = JSON.parse(await readFile(filePath, "utf-8"));
|
|
} catch (err: any) {
|
|
if (err.code !== "ENOENT")
|
|
throw err;
|
|
data = typeof fallback === "function" ? fallback() : fallback;
|
|
}
|
|
return data;
|
|
}
|
|
|
|
export async function readSchedule() {
|
|
return readJson(schedulePath, generateDemoSchedule);
|
|
}
|
|
|
|
export async function writeSchedule(schedule: Schedule) {
|
|
await writeFile(schedulePath, JSON.stringify(schedule, undefined, "\t") + "\n", "utf-8");
|
|
}
|
|
|
|
export async function readSubscriptions() {
|
|
let subscriptions = await readJson<Subscription[]>(subscriptionsPath, []);
|
|
if (subscriptions.length && "keys" in subscriptions[0]) {
|
|
// Discard old format
|
|
subscriptions = [];
|
|
}
|
|
return subscriptions;
|
|
}
|
|
|
|
export async function writeSubscriptions(subscriptions: Subscription[]) {
|
|
await writeFile(subscriptionsPath, JSON.stringify(subscriptions, undefined, "\t") + "\n", "utf-8");
|
|
}
|