From ba0c7fa9de5cb4805b109a1c028add6e3b223a09 Mon Sep 17 00:00:00 2001 From: cupcakearmy Date: Mon, 9 Sep 2019 12:11:24 +0200 Subject: [PATCH] don't make the app crash when the config file is already present but empty. --- src/index.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index f8779b7..839c1d8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,14 +1,17 @@ -import { readFileSync, writeFileSync, lstatSync } from 'fs' +import { readFileSync, writeFileSync } from 'fs' import { resolve } from 'path' -import yaml from 'yaml' +import * as yaml from 'yaml' + + type AllowedYamlTypes = string | number | boolean type AllowedTypes = AllowedYamlTypes | AllowedYamlTypes[] -export default class Memento { +export default class Memiens { private readonly file: string private state: any + constructor(file: string) { this.file = resolve(file) try { @@ -19,7 +22,8 @@ export default class Memento { } } - public get(setting: string, defaultValue: AllowedTypes | undefined = undefined): AllowedTypes { + + public get(setting: string, defaultValue: T | undefined = undefined): T { const props = setting.split('.') let root = this.state try { @@ -29,13 +33,13 @@ export default class Memento { } if (root) return root if (defaultValue) { - // @ts-ignore this.set(setting, defaultValue) return defaultValue } throw new Error('Could not load the setting') } + public set(setting: string, value: AllowedTypes): void { const props = setting.split('.') let root = this.state @@ -47,10 +51,12 @@ export default class Memento { this.save() } + private read() { - this.state = yaml.parse(readFileSync(this.file, 'utf-8')) + this.state = yaml.parse(readFileSync(this.file, 'utf-8')) || {} } + private save() { writeFileSync(this.file, yaml.stringify(this.state), 'utf-8') }