diff --git a/backend/UserConfig.ts b/backend/UserConfig.ts index 52cd546..36b59ce 100644 --- a/backend/UserConfig.ts +++ b/backend/UserConfig.ts @@ -1,5 +1,7 @@ import fs from 'fs-extra'; +import { path } from '@tycrek/joint'; import { UserConfiguration, UserConfigTypeChecker } from 'ass'; +import { log } from './log'; /** * Returns a boolean if the provided value is a number @@ -27,11 +29,19 @@ const Checkers: UserConfigTypeChecker = { } export class UserConfig { - private config: UserConfiguration; - public getConfig = () => this.config; + private static config: UserConfiguration; + private ready = false; + + public getConfig = () => UserConfig.config; + public getReady = () => this.ready; constructor(config?: UserConfiguration) { - if (config != null) this.config = this.parseConfig(config); + + // Typically this would only happen during first-time setup (for now) + if (config != null) { + UserConfig.config = this.parseConfig(config); + this.ready = true; + } } private parseConfig(config: UserConfiguration) { @@ -44,4 +54,49 @@ export class UserConfig { // All is fine, carry on! return config; } + + /** + * Save the config file to disk + */ + public saveConfigFile(): Promise { + return new Promise(async (resolve, reject) => { + try { + + // Only save is the config has been parsed + if (!this.ready) throw new Error('Config not ready to be saved!'); + + // Write to file + await fs.writeFile(path.join('userconfig.json'), JSON.stringify(UserConfig.config, null, '\t')); + + resolve(void 0); + } catch (err) { + log.error('Failed to save config file!'); + console.error(err); + reject(err); + } + }); + } + + /** + * Reads the config file from disk + */ + public readConfigFile(): Promise { + return new Promise(async (resolve, reject) => { + try { + + // Read the file data + const data = (await fs.readFile(path.join('userconfig.json'))).toString(); + + // Ensure the config is valid + UserConfig.config = this.parseConfig(data as unknown as UserConfiguration); + this.ready = true; + + resolve(void 0); + } catch (err) { + log.error('Failed to read config file!'); + console.error(err); + reject(err); + } + }); + } }