Refactor code saving data
Move the code dealing with saving and loading data to server/database to gather it all up into one place.
This commit is contained in:
parent
754d175ce2
commit
6ea3567c94
8 changed files with 64 additions and 58 deletions
44
server/database.ts
Normal file
44
server/database.ts
Normal file
|
@ -0,0 +1,44 @@
|
|||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { Schedule } from "~/shared/types/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 = "schedule.json"
|
||||
const subscriptionsPath = "push-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 an empty schedule if nothing is stored yet.
|
||||
schedule = {
|
||||
locations: [],
|
||||
events: [],
|
||||
}
|
||||
}
|
||||
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");
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue