diff --git a/src/gadgetbridge/client.ts b/src/gadgetbridge/client.ts index e598ea9..44541b7 100644 --- a/src/gadgetbridge/client.ts +++ b/src/gadgetbridge/client.ts @@ -1,3 +1,4 @@ +import { watchFile } from "node:fs"; import { DatabaseSync } from "node:sqlite"; export type StepRow = { @@ -7,10 +8,23 @@ export type StepRow = { export class GadgetbridgeClient { private db: DatabaseSync; + private readonly dbPath: string; + private readonly oldDbPath: string; constructor(dbPath: string, oldDbPath: string) { - this.db = new DatabaseSync(dbPath, { open: true }); - this.db.exec(`ATTACH DATABASE '${oldDbPath}' AS old`); + this.dbPath = dbPath; + this.oldDbPath = oldDbPath; + this.db = this.openDb(); + watchFile(dbPath, { interval: 20 * 60 * 1000 }, () => { + try { this.db.close(); } catch {} + this.db = this.openDb(); + }); + } + + private openDb(): DatabaseSync { + const db = new DatabaseSync(this.dbPath, { open: true }); + db.exec(`ATTACH DATABASE '${this.oldDbPath}' AS old`); + return db; } getStepsPerDay(fromTimestamp: number, toTimestamp: number): StepRow[] {