github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/kat/src/lib/config.ts (about) 1 // Copyright © 2021 Kaleido, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 import { promisify } from 'util'; 16 import { readFile } from 'fs'; 17 import Ajv from 'ajv'; 18 import configSchema from '../schemas/config.json'; 19 import * as utils from './utils'; 20 import { IConfig } from './interfaces'; 21 import path from 'path'; 22 import chokidar, { FSWatcher } from 'chokidar'; 23 24 const log = utils.getLogger('lib/config.ts'); 25 26 const asyncReadFile = promisify(readFile); 27 const ajv = new Ajv(); 28 const validateConfig = ajv.compile(configSchema); 29 const configFilePath = path.join(utils.constants.DATA_DIRECTORY, utils.constants.CONFIG_FILE_NAME); 30 31 export let config: IConfig; 32 let fsWatcher: FSWatcher; 33 let configChangeListener: () => void; 34 35 export const init = async (listener: () => void) => { 36 await loadConfigFile(); 37 watchConfigFile(); 38 configChangeListener = listener; 39 }; 40 41 const loadConfigFile = async () => { 42 try { 43 const data = JSON.parse(await asyncReadFile(configFilePath, 'utf8')); 44 if(validateConfig(data)) { 45 config = data; 46 } else { 47 throw new Error('Invalid configuration file'); 48 } 49 } catch(err) { 50 throw new Error(`Failed to read configuration file. ${err}`); 51 } 52 }; 53 54 const watchConfigFile = () => { 55 fsWatcher = chokidar.watch(configFilePath, { ignoreInitial: true }).on('change', async () => { 56 try { 57 await loadConfigFile(); 58 log.info('Loaded configuration file changes'); 59 configChangeListener(); 60 } catch(err) { 61 log.error(`Failed to load configuration file. ${err}`); 62 } 63 }); 64 }; 65 66 export const shutDown = () => { 67 fsWatcher.close(); 68 };