Add Configuration loading and fetching

This commit is contained in:
2022-02-27 17:31:38 +07:00
parent e3307cf5c1
commit 015909457f
+24 -2
View File
@@ -3,6 +3,7 @@ import path from "path";
import Logger from "../libs/Logger"; import Logger from "../libs/Logger";
const ConfigurationData: any = [];
class Configuration { class Configuration {
public init(): void { public init(): void {
@@ -12,6 +13,29 @@ class Configuration {
} }
this.copyExampleIfNotExists("Ping.json"); this.copyExampleIfNotExists("Ping.json");
this.copyExampleIfNotExists("ServiceAnnouncement.json"); this.copyExampleIfNotExists("ServiceAnnouncement.json");
this.loadConfig("Ping.json");
this.loadConfig("ServiceAnnouncement.json");
}
public loadConfig(configFileName: string): void {
const dir = path.join(process.cwd(), 'configs/');
if (!fs.existsSync(path.join(dir, configFileName)))
throw new Error(`Config file ${configFileName} does not exist`);
const config = JSON.parse(fs.readFileSync(path.join(dir, configFileName)).toString());
ConfigurationData[configFileName.replace(/\.[^/.]+$/, "")] = config;
}
public getConfig(key?: string) {
if(!key)
return ConfigurationData;
else {
if(ConfigurationData[key])
return ConfigurationData[key];
else
throw new Error(`No configuration found for ${key}`);
}
} }
private copyExampleIfNotExists(file: string): void { private copyExampleIfNotExists(file: string): void {
@@ -21,8 +45,6 @@ class Configuration {
} }
} }
// TODO: Make a real providers like Environment
} }
export default new Configuration(); export default new Configuration();