Skip to content
This repository has been archived by the owner on Jun 17, 2022. It is now read-only.

Commit

Permalink
Add logging to lowdb storage service (#188)
Browse files Browse the repository at this point in the history
  • Loading branch information
cscharf committed Oct 20, 2020
1 parent d84d6da commit 4cd20f0
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/services/lowdbStorage.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -13,37 +14,48 @@ 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;
}
}
}

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.');
}
}

Expand Down

0 comments on commit 4cd20f0

Please sign in to comment.