import { safeDump , safeLoad , JSON_SCHEMA } from 'js-yaml' ; import { promisify } from 'util' ; import { readFile , writeFile } from 'fs' ; import { configSchema , ConfigSchema } from './schema' ; import { createLogger } from '../log' ; const log = createLogger ( __filename ) ; const readFileAsync = promisify ( readFile ) ; const writeFileAsync = promisify ( writeFile ) ; export const load = async ( path ) : Promise < ConfigSchema > => { let data ; try { data = await readFileAsync ( path ) ; } catch ( err ) { log . error ( { err } , 'error while reading config file:' , path , { err } ) ; return null ; } const object = safeLoad ( data . toString ( ) , { schema : JSON_SCHEMA } ) ; const validation = configSchema . validate ( object ) ; if ( validation . error ) { throw validation . error ; } return < ConfigSchema > validation . value ; } ; export const save = async ( config , path ) : Promise < void > => { const validation = configSchema . validate ( config ) ; if ( validation . error ) { log . error ( { err : validation . error } , 'error while saving config' ) ; return Promise . reject ( validation . error ) ; } const yaml = safeDump ( config , { schema : JSON_SCHEMA } ) . replace ( /\n {0,2}[^ ]/g , '\n$&' ) ; const header = '# Do not edit this file while SSHMon is running.\n# It will be overwritten on config change.\n\n' ; return writeFileAsync ( path , `${ header }${ yaml }` ) ; } ;