From 2870b7472bbb91893561c5c6603294e32bccd57d Mon Sep 17 00:00:00 2001 From: Kyle Spearrin Date: Tue, 9 Oct 2018 15:18:25 -0400 Subject: [PATCH] re-write data file if malformed json --- src/services/lowdbStorage.service.ts | 38 +++++++++++++++++----------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/src/services/lowdbStorage.service.ts b/src/services/lowdbStorage.service.ts index 581c48291a..50c01e66b3 100644 --- a/src/services/lowdbStorage.service.ts +++ b/src/services/lowdbStorage.service.ts @@ -11,6 +11,7 @@ import { Utils } from '../misc/utils'; export class LowdbStorageService implements StorageService { private db: lowdb.LowdbSync; private defaults: any; + private dataFilePath: string; constructor(defaults?: any, dir?: string, private allowCache = false) { this.defaults = defaults; @@ -20,25 +21,30 @@ export class LowdbStorageService implements StorageService { if (!fs.existsSync(dir)) { NodeUtils.mkdirpSync(dir, '700'); } - const p = path.join(dir, 'data.json'); - adapter = new FileSync(p); + this.dataFilePath = path.join(dir, 'data.json'); + adapter = new FileSync(this.dataFilePath); + } + try { + this.db = lowdb(adapter); + } catch (e) { + if (e instanceof SyntaxError) { + fs.writeFileSync(this.dataFilePath, ''); + this.db = lowdb(adapter); + } else { + throw e; + } } - this.db = lowdb(adapter); } init() { if (this.defaults != null) { - if (!this.allowCache) { - this.db.read(); - } + this.readForNoCache(); this.db.defaults(this.defaults).write(); } } get(key: string): Promise { - if (!this.allowCache) { - this.db.read(); - } + this.readForNoCache(); const val = this.db.get(key).value(); if (val == null) { return Promise.resolve(null); @@ -47,18 +53,20 @@ export class LowdbStorageService implements StorageService { } save(key: string, obj: any): Promise { - if (!this.allowCache) { - this.db.read(); - } + this.readForNoCache(); this.db.set(key, obj).write(); return Promise.resolve(); } remove(key: string): Promise { - if (!this.allowCache) { - this.db.read(); - } + this.readForNoCache(); this.db.unset(key).write(); return Promise.resolve(); } + + private readForNoCache() { + if (!this.allowCache) { + this.db.read(); + } + } }