diff --git a/src/server/index.ts b/src/server/index.ts index 334113b..91f12bf 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -8,6 +8,7 @@ import APIRouter from "./routes/api.js" import { fileURLToPath } from "url" import { dirname } from "path" import config from "./lib/config.js" +import { dbs } from "./lib/dbfile.js" const app = new Hono({strict: false}) @@ -60,8 +61,18 @@ if (config.forceSSL) { // discord let files = new Files(config) +// ts screams at me if i don't +// use a function here. +// i'm inflight so +// i'm too lazy to figure this out const apiRouter = new APIRouter(files) -apiRouter.loadAPIMethods().then(() => { +apiRouter.loadAPIMethods().then(async () => + Promise.all( + Object.values(dbs) + .map(e => e.readInProgress) + .filter(e => Boolean(e)) + ) +).then(() => { app.route("/", apiRouter.root) console.log("API OK!") diff --git a/src/server/lib/dbfile.ts b/src/server/lib/dbfile.ts index c1a8a69..a336c2d 100644 --- a/src/server/lib/dbfile.ts +++ b/src/server/lib/dbfile.ts @@ -4,6 +4,7 @@ import path from "node:path" const DATADIR = `./.data` const TICK = 500 +export let dbs: Record> = {} export type Write = ReturnType @@ -86,10 +87,14 @@ export default class DbFile { private rewriteNeeded: boolean = false private readonly files: string[] + readInProgress?: Promise + constructor(name: string, defaultData: Structure) { this.name = name this.data = defaultData this.files = [`${name}.json`, `${name}-b.json`].map(e => path.join(DATADIR, e)) + + dbs[this.name] = this } private async findAvailable() { @@ -148,15 +153,25 @@ export default class DbFile { return JSON.parse((await readFile(path)).toString()) } - async read() { + private async _read() { let availFiles = await this.findAvailable() + + if (availFiles.length == 0) return + for (let x of availFiles) { let data = await this.tryRead(x).catch(_ => null) if (data !== null) { this.data = data - break + return } } + + throw new Error(`Failed to read any of the available files for DbFile ${this.name}`) + } + + read() { + this.readInProgress = this._read() + return this.readInProgress } } \ No newline at end of file