github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/kat/src/lib/settings.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 Ajv from 'ajv'; 16 import { promisify } from 'util'; 17 import { readFile, writeFile } from 'fs'; 18 import path from 'path'; 19 import * as utils from './utils'; 20 import { ISettings } from './interfaces'; 21 import settingsSchema from '../schemas/settings.json'; 22 import RequestError from './request-handlers'; 23 24 const log = utils.getLogger('lib/settings.ts'); 25 26 const asyncReadFile = promisify(readFile); 27 const asyncWriteFile = promisify(writeFile); 28 const ajv = new Ajv(); 29 const validateSettings = ajv.compile(settingsSchema); 30 export let settings: ISettings; 31 32 const settingsFilePath = path.join(utils.constants.DATA_DIRECTORY, utils.constants.SETTINGS_FILE_NAME); 33 34 export const init = async () => { 35 await readSettingsFile() 36 }; 37 38 const readSettingsFile = async () => { 39 try { 40 const values = JSON.parse(await asyncReadFile(settingsFilePath, 'utf8')); 41 if(!validateSettings(values)) { 42 throw new Error('Invalid content'); 43 } 44 settings = values; 45 } catch(err) { 46 if(err.errno === -2) { 47 settings = { 48 clientEvents: [] 49 }; 50 } else { 51 throw new Error(`Failed to read settings file. ${err}`); 52 } 53 } 54 }; 55 56 export const updateSettings = async (key: string, value: any) => { 57 const updatedSettings = {...settings, [key]: value}; 58 if (!validateSettings(updatedSettings)) { 59 throw new RequestError('Invalid Settings', 400); 60 } 61 settings = updatedSettings; 62 await persistSettings(); 63 }; 64 65 export const setClientEvents = (clientEvents: string[]) => { 66 settings.clientEvents = clientEvents; 67 persistSettings(); 68 }; 69 70 const persistSettings = () => { 71 try { 72 asyncWriteFile(settingsFilePath, JSON.stringify(settings)); 73 } catch(err) { 74 log.error(`Failed to persist settings. ${err}`); 75 } 76 };