Make lowdbStorageService wait until initialised (#605)
* Make lowdbStorageService wait until initialised * Fix prettier
This commit is contained in:
parent
957e010036
commit
ddcfe23367
|
@ -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<any>;
|
||||
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<any>;
|
||||
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<T>(key: string): Promise<T> {
|
||||
async get<T>(key: string): Promise<T> {
|
||||
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<any> {
|
||||
async save(key: string, obj: any): Promise<any> {
|
||||
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<any> {
|
||||
async remove(key: string): Promise<any> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue