Add logging to lowdb storage service (#188)

This commit is contained in:
Chad Scharf 2020-10-20 09:33:30 -04:00 committed by GitHub
parent d84d6da7f7
commit 4cd20f0fa8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 13 additions and 1 deletions

View File

@ -3,6 +3,7 @@ import * as lowdb from 'lowdb';
import * as FileSync from 'lowdb/adapters/FileSync';
import * as path from 'path';
import { LogService } from '../abstractions/log.service';
import { StorageService } from '../abstractions/storage.service';
import { NodeUtils } from '../misc/nodeUtils';
@ -13,28 +14,37 @@ export class LowdbStorageService implements StorageService {
private defaults: any;
private dataFilePath: string;
constructor(defaults?: any, dir?: string, private allowCache = false) {
constructor(private logService: LogService, defaults?: any, dir?: string, private allowCache = false) {
this.defaults = defaults;
this.logService.info('Initializing lowdb storage service.');
let adapter: lowdb.AdapterSync<any>;
if (Utils.isNode && dir != null) {
if (!fs.existsSync(dir)) {
this.logService.warning(`Could not find dir, "${dir}"; creating it instead.`);
NodeUtils.mkdirpSync(dir, '700');
this.logService.info(`Created dir "${dir}".`);
}
this.dataFilePath = path.join(dir, 'data.json');
if (!fs.existsSync(this.dataFilePath)) {
this.logService.warning(`Could not find data file, "${this.dataFilePath}"; creating it instead.`);
fs.writeFileSync(this.dataFilePath, '', { mode: 0o600 });
fs.chmodSync(this.dataFilePath, 0o600);
this.logService.info(`Created data file "${this.dataFilePath}" with chmod 600.`);
}
adapter = new FileSync(this.dataFilePath);
}
try {
this.logService.info('Attempting to create lowdb storage adapter.');
this.db = lowdb(adapter);
this.logService.info('Successfuly created lowdb storage adapter.');
} catch (e) {
if (e instanceof SyntaxError) {
this.logService.warning(`Error creating lowdb storage adapter, "${e.message}"; emptying data file.`);
adapter.write({});
this.db = lowdb(adapter);
} else {
this.logService.error(`Error creating lowdb storage adapter, "${e.message}".`);
throw e;
}
}
@ -42,8 +52,10 @@ export class LowdbStorageService implements StorageService {
init() {
if (this.defaults != null) {
this.logService.info('Writing defaults.');
this.readForNoCache();
this.db.defaults(this.defaults).write();
this.logService.info('Successfully wrote defaults to db.');
}
}