mirror of
https://github.com/mollersuite/monofile.git
synced 2024-11-22 05:46:26 -08:00
dbfile stuff
This commit is contained in:
parent
426e057f12
commit
3e834bfda2
|
@ -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!")
|
||||
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in a new issue