dbfile stuff

This commit is contained in:
May 2024-06-17 16:43:34 -07:00
parent 426e057f12
commit 3e834bfda2
2 changed files with 29 additions and 3 deletions

View file

@ -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!")

View file

@ -4,6 +4,7 @@ import path from "node:path"
const DATADIR = `./.data`
const TICK = 500
export let dbs: Record<string, DbFile<any>> = {}
export type Write = ReturnType<typeof writeFile>
@ -86,10 +87,14 @@ export default class DbFile<Structure extends ({}|[])> {
private rewriteNeeded: boolean = false
private readonly files: string[]
readInProgress?: Promise<void>
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<Structure extends ({}|[])> {
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
}
}