|
| 1 | +/** |
| 2 | + * Name: config-manager.ts |
| 3 | + * Description: Config Manager Factory |
| 4 | + * Author: Ovidiu Barabula <lectii2008@gmail.com> |
| 5 | + * @since 0.1.0 |
| 6 | + */ |
| 7 | + |
| 8 | +import PackageJsonConfigReader, { |
| 9 | + Config, |
| 10 | + ConfigReaderFactory, |
| 11 | + IConfigReader, |
| 12 | +} from './package-json-config-reader'; |
| 13 | + |
| 14 | + |
| 15 | +export interface IConfigManager { |
| 16 | + has(key: string): boolean; |
| 17 | + get(key?: string): any; |
| 18 | + set(key: string, value: any): Promise<boolean>; |
| 19 | +} |
| 20 | + |
| 21 | +/** |
| 22 | + * Create Configuration manager |
| 23 | + * @param namespace Configuration namespace, usually app name (used in package.json { config: { <namespace>: {} } }) |
| 24 | + * @param customReader Custom ConfigReader |
| 25 | + */ |
| 26 | +async function ConfigManagerFactory( |
| 27 | + namespace: string, |
| 28 | + customReader?: ConfigReaderFactory, |
| 29 | +): Promise<IConfigManager> { |
| 30 | + let configReader: IConfigReader; |
| 31 | + |
| 32 | + // Check for custom config reader |
| 33 | + if (customReader && typeof customReader === 'function') { |
| 34 | + // Initialize custom config reader |
| 35 | + configReader = customReader(namespace); |
| 36 | + } else { |
| 37 | + // If not, stick with the default config reader |
| 38 | + configReader = await PackageJsonConfigReader(namespace); |
| 39 | + } |
| 40 | + |
| 41 | + // Get the configuration contents |
| 42 | + const config: Config = await configReader.fetch(); |
| 43 | + |
| 44 | + |
| 45 | + /** |
| 46 | + * Check if key exists in config |
| 47 | + * @param key Configuration option key |
| 48 | + */ |
| 49 | + function has(key: string): boolean { |
| 50 | + return config.hasOwnProperty(key); |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + /** |
| 55 | + * Retrieve value from configuration |
| 56 | + * @param key Configuration option key |
| 57 | + */ |
| 58 | + function get(key?: string): Config | any { |
| 59 | + if (typeof key === 'undefined') { |
| 60 | + return config; |
| 61 | + } |
| 62 | + |
| 63 | + return config[key]; |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | + /** |
| 68 | + * Set new value for configuration option |
| 69 | + * @param key Configuration option key |
| 70 | + * @param value New value to be set |
| 71 | + */ |
| 72 | + async function set(key: string, value: any): Promise<boolean> { |
| 73 | + config[key] = value; |
| 74 | + const saved = await configReader.update(config); |
| 75 | + return saved; |
| 76 | + } |
| 77 | + |
| 78 | + // Returning config manager public API |
| 79 | + return Object.freeze({ |
| 80 | + get, |
| 81 | + has, |
| 82 | + set, |
| 83 | + }); |
| 84 | +} |
| 85 | + |
| 86 | +export default ConfigManagerFactory; |
0 commit comments