@btc-vision/bsi-common
Version:
Common library for OP_NET.
84 lines (83 loc) • 3.14 kB
JavaScript
import { DebugLevel, Logger } from '@btc-vision/logger';
import fs from 'fs';
import toml from 'toml';
import '../utils/Globals.js';
export class ConfigManager extends Logger {
constructor(fullFileName, preload = true) {
super();
this.logColor = '#c71585';
this.config = this.getDefaultConfig();
if (preload)
this.loadConfig(fullFileName);
}
getDefaultConfig() {
const config = {
DEBUG_LEVEL: DebugLevel.INFO,
LOG_FOLDER: '',
DATABASE: {
DATABASE_NAME: '',
HOST: '',
PORT: 0,
AUTH: {
USERNAME: '',
PASSWORD: '',
},
},
};
return config;
}
verifyConfig(parsedConfig) {
if (parsedConfig.DEBUG_LEVEL) {
if (typeof parsedConfig.DEBUG_LEVEL !== 'number') {
throw new Error(`Oops the property DEBUG_LEVEL is not a number.`);
}
}
if (parsedConfig.LOG_FOLDER) {
if (typeof parsedConfig.LOG_FOLDER !== 'string') {
throw new Error(`Oops the property LOG_FOLDER is not a string.`);
}
}
if (parsedConfig.DATABASE) {
if (typeof parsedConfig.DATABASE.DATABASE_NAME !== 'string') {
throw new Error(`Oops the property DATABASE.DATABASE_NAME is not a string.`);
}
if (typeof parsedConfig.DATABASE.HOST !== 'string') {
throw new Error(`Oops the property DATABASE.HOST is not a string.`);
}
if (typeof parsedConfig.DATABASE.PORT !== 'number') {
throw new Error(`Oops the property DATABASE.PORT is not a number.`);
}
if (parsedConfig.DATABASE.AUTH) {
if (typeof parsedConfig.DATABASE.AUTH.USERNAME !== 'string') {
throw new Error(`Oops the property DATABASE.AUTH.USERNAME is not a string.`);
}
if (typeof parsedConfig.DATABASE.AUTH.PASSWORD !== 'string') {
throw new Error(`Oops the property DATABASE.AUTH.PASSWORD is not a string.`);
}
}
}
}
parsePartialConfig(parsedConfig) {
this.verifyConfig(parsedConfig);
this.config.DATABASE = {
...this.config.DATABASE,
...parsedConfig.DATABASE,
};
this.config.DEBUG_LEVEL = parsedConfig.DEBUG_LEVEL || this.config.DEBUG_LEVEL;
this.config.LOG_FOLDER = parsedConfig.LOG_FOLDER || this.config.LOG_FOLDER;
}
loadConfig(fullFileName) {
const config = fs.readFileSync(fullFileName, 'utf-8');
if (!config) {
throw new Error('Failed to load config file. Please ensure that the config file exists.');
}
try {
const parsedConfig = toml.parse(config);
this.parsePartialConfig(parsedConfig);
}
catch (e) {
const error = e;
this.error(`Failed to load config file. {Details: ${error.stack}}`);
}
}
}