1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-10-19 07:35:48 +02:00
bitwarden-browser/src/services/lowdbStorage.service.ts

73 lines
1.9 KiB
TypeScript
Raw Normal View History

2018-05-31 15:07:56 +02:00
import * as fs from 'fs';
import * as lowdb from 'lowdb';
import * as FileSync from 'lowdb/adapters/FileSync';
import * as path from 'path';
import { StorageService } from '../abstractions/storage.service';
import { NodeUtils } from '../misc/nodeUtils';
import { Utils } from '../misc/utils';
export class LowdbStorageService implements StorageService {
private db: lowdb.LowdbSync<any>;
private defaults: any;
2018-10-09 21:18:25 +02:00
private dataFilePath: string;
2018-05-31 15:07:56 +02:00
2018-06-05 20:44:13 +02:00
constructor(defaults?: any, dir?: string, private allowCache = false) {
2018-05-31 15:07:56 +02:00
this.defaults = defaults;
let adapter: lowdb.AdapterSync<any>;
if (Utils.isNode && dir != null) {
if (!fs.existsSync(dir)) {
2018-08-28 04:59:50 +02:00
NodeUtils.mkdirpSync(dir, '700');
2018-05-31 15:07:56 +02:00
}
2018-10-09 21:18:25 +02:00
this.dataFilePath = path.join(dir, 'data.json');
adapter = new FileSync(this.dataFilePath);
}
try {
this.db = lowdb(adapter);
} catch (e) {
if (e instanceof SyntaxError) {
2018-10-09 21:31:52 +02:00
adapter.write({});
2018-10-09 21:18:25 +02:00
this.db = lowdb(adapter);
} else {
throw e;
}
2018-05-31 15:07:56 +02:00
}
}
init() {
if (this.defaults != null) {
2018-10-09 21:18:25 +02:00
this.readForNoCache();
2018-06-05 20:44:13 +02:00
this.db.defaults(this.defaults).write();
2018-05-31 15:07:56 +02:00
}
}
get<T>(key: string): Promise<T> {
2018-10-09 21:18:25 +02:00
this.readForNoCache();
2018-06-05 20:44:13 +02:00
const val = this.db.get(key).value();
2018-06-01 17:51:48 +02:00
if (val == null) {
return Promise.resolve(null);
}
2018-05-31 15:07:56 +02:00
return Promise.resolve(val as T);
}
save(key: string, obj: any): Promise<any> {
2018-10-09 21:18:25 +02:00
this.readForNoCache();
2018-06-05 20:44:13 +02:00
this.db.set(key, obj).write();
2018-05-31 15:07:56 +02:00
return Promise.resolve();
}
remove(key: string): Promise<any> {
2018-10-09 21:18:25 +02:00
this.readForNoCache();
this.db.unset(key).write();
return Promise.resolve();
}
private readForNoCache() {
2018-06-05 20:44:13 +02:00
if (!this.allowCache) {
this.db.read();
}
2018-05-31 15:07:56 +02:00
}
}