From 015909457fa1de27a6acd7faefcb5bc4f2ef5442 Mon Sep 17 00:00:00 2001 From: Yuzu Date: Sun, 27 Feb 2022 17:31:38 +0700 Subject: [PATCH] Add Configuration loading and fetching --- src/providers/Configuration.ts | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/providers/Configuration.ts b/src/providers/Configuration.ts index 91c1a79..8a59f9f 100644 --- a/src/providers/Configuration.ts +++ b/src/providers/Configuration.ts @@ -3,6 +3,7 @@ import path from "path"; import Logger from "../libs/Logger"; +const ConfigurationData: any = []; class Configuration { public init(): void { @@ -12,6 +13,29 @@ class Configuration { } this.copyExampleIfNotExists("Ping.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 { @@ -21,8 +45,6 @@ class Configuration { } } - // TODO: Make a real providers like Environment - } export default new Configuration();