Pull JSON read file logic into a function
This commit is contained in:
parent
8da4b02154
commit
b4934005ae
1 changed files with 13 additions and 22 deletions
|
@ -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<T>(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<PushSubscriptionJSON[]>(subscriptionsPath, []);
|
||||
return subscriptions;
|
||||
}
|
||||
|
||||
export async function writeSubscriptions(subscriptions: PushSubscriptionJSON[]) {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue