From ddcfe2336740549c97523d9d75e602f905f0431c Mon Sep 17 00:00:00 2001 From: Thomas Rittson <31796059+eliykat@users.noreply.github.com> Date: Thu, 13 Jan 2022 06:18:54 +1000 Subject: [PATCH] Make lowdbStorageService wait until initialised (#605) * Make lowdbStorageService wait until initialised * Fix prettier --- node/src/services/lowdbStorage.service.ts | 24 ++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/node/src/services/lowdbStorage.service.ts b/node/src/services/lowdbStorage.service.ts index 1dcaaf1ad8..053961159f 100644 --- a/node/src/services/lowdbStorage.service.ts +++ b/node/src/services/lowdbStorage.service.ts @@ -7,12 +7,14 @@ import { LogService } from "jslib-common/abstractions/log.service"; import { StorageService } from "jslib-common/abstractions/storage.service"; import { NodeUtils } from "jslib-common/misc/nodeUtils"; +import { sequentialize } from "jslib-common/misc/sequentialize"; import { Utils } from "jslib-common/misc/utils"; export class LowdbStorageService implements StorageService { protected dataFilePath: string; private db: lowdb.LowdbSync; private defaults: any; + private ready = false; constructor( protected logService: LogService, @@ -23,7 +25,12 @@ export class LowdbStorageService implements StorageService { this.defaults = defaults; } + @sequentialize(() => "lowdbStorageInit") async init() { + if (this.ready) { + return; + } + this.logService.info("Initializing lowdb storage service."); let adapter: lowdb.AdapterSync; if (Utils.isNode && this.dir != null) { @@ -81,9 +88,12 @@ export class LowdbStorageService implements StorageService { this.logService.info("Successfully wrote defaults to db."); }); } + + this.ready = true; } - get(key: string): Promise { + async get(key: string): Promise { + await this.waitForReady(); return this.lockDbFile(() => { this.readForNoCache(); const val = this.db.get(key).value(); @@ -99,7 +109,8 @@ export class LowdbStorageService implements StorageService { return this.get(key).then((v) => v != null); } - save(key: string, obj: any): Promise { + async save(key: string, obj: any): Promise { + await this.waitForReady(); return this.lockDbFile(() => { this.readForNoCache(); this.db.set(key, obj).write(); @@ -108,7 +119,8 @@ export class LowdbStorageService implements StorageService { }); } - remove(key: string): Promise { + async remove(key: string): Promise { + await this.waitForReady(); return this.lockDbFile(() => { this.readForNoCache(); this.db.unset(key).write(); @@ -127,4 +139,10 @@ export class LowdbStorageService implements StorageService { this.db.read(); } } + + private async waitForReady() { + if (!this.ready) { + await this.init(); + } + } }