90 lines
2.2 KiB
TypeScript
90 lines
2.2 KiB
TypeScript
import fs from 'node:fs';
|
|
import _ from 'lodash';
|
|
|
|
export type configObject = Record<any, any>;
|
|
|
|
/**
|
|
* This class is responsible to save/edit config files.
|
|
*
|
|
* @export
|
|
* @class config
|
|
* @typedef {config}
|
|
*/
|
|
export default class config {
|
|
#configPath: string;
|
|
//global = {[key: string] : string}
|
|
global: configObject;
|
|
|
|
/**
|
|
* Creates an instance of config.
|
|
*
|
|
* @constructor
|
|
* @param {string} configPath Path to config file.
|
|
* @param {object} configPreset Default config object with default values.
|
|
*/
|
|
constructor(configPath: string, configPreset: object) {
|
|
this.#configPath = configPath;
|
|
this.global = configPreset;
|
|
|
|
try {
|
|
// Read config
|
|
const data = fs.readFileSync(this.#configPath, 'utf8');
|
|
|
|
// Extend config with missing parameters from configPreset.
|
|
this.global = _.defaultsDeep(JSON.parse(data), this.global);
|
|
// Save config.
|
|
this.save_config();
|
|
} catch (err) {
|
|
// If file does not exist, create it.
|
|
if (err.code === 'ENOENT') {
|
|
console.log(`Config file does not exist. Creating it at ${this.#configPath} now.`);
|
|
this.save_config();
|
|
return;
|
|
}
|
|
console.error(`Could not read config file at ${this.#configPath} due to: ${err}`);
|
|
// Exit process.
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Saves the jsonified config object to the config file.
|
|
*/
|
|
save_config() {
|
|
try {
|
|
fs.writeFileSync(this.#configPath, JSON.stringify(this.global, null, 8));
|
|
} catch (err) {
|
|
console.error(`Could not write config file at ${this.#configPath} due to: ${err}`);
|
|
return;
|
|
}
|
|
console.log(`Successfully written config file to ${this.#configPath}`);
|
|
}
|
|
}
|
|
|
|
/*
|
|
|
|
**** Example ****
|
|
|
|
import configHandler from './assets/configHandler.js';
|
|
|
|
// Create a new config instance.
|
|
export const config = new ConfigHandler(__path + '/config.json', {
|
|
db_connection_string: 'mysql://USER:PASSWORD@HOST:3306/DATABASE',
|
|
http_listen_address: '127.0.0.1',
|
|
http_port: 3000,
|
|
sentry_dsn: 'https://ID@sentry.example.com/PROJECTID',
|
|
debug: false
|
|
});
|
|
|
|
|
|
console.log('Base Config:');
|
|
console.log(config.global);
|
|
|
|
console.log('Add some new key to config and call save_config.');
|
|
config.global.NewKey = 'ThisIsANewKey!'
|
|
config.save_config()
|
|
|
|
console.log('Complete Config:');
|
|
console.log(config.global);
|
|
*/
|