1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-11-06 09:20:43 +01:00

Make lowdbStorageService wait until initialised (#605)

* Make lowdbStorageService wait until initialised

* Fix prettier
This commit is contained in:
Thomas Rittson 2022-01-13 06:18:54 +10:00 committed by GitHub
parent 957e010036
commit ddcfe23367
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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();
}
}
}