import * as file from './file' ; import * as logging from './logging' ; export interface JsonConfig < T > { data ( ) : T ; write ( ) ; } export function loadFileConfig < T > ( filename ) { const text = file . readFileIfExists ( filename ) ; let dataJson = { } as T ; if ( text ) { dataJson = JSON . parse ( text ) as T ; } return new FileConfig < T > ( filename , dataJson ) ; } export class FileConfig < T > implements JsonConfig < T > { constructor ( private filename , private dataJson ) { } data ( ) { return this . dataJson ; } write ( ) { try { file . atomicWriteFileSync ( this . filename , JSON . stringify ( this . dataJson ) ) ; } catch ( error ) { logging . error ( `Error writing config ${ this . filename } ${ error }` ) ; } } } export class ChildConfig < T > implements JsonConfig < T > { constructor ( private parentConfig , private dataJson ) { } data ( ) { return this . dataJson ; } write ( ) { this . parentConfig . write ( ) ; } } export class DelayedConfig < T > implements JsonConfig < T > { private dirty = false ; constructor ( private config , writePeriodMs ) { setInterval ( ( ) => { if ( ! this . dirty ) { return ; } this . config . write ( ) ; this . dirty = false ; } , writePeriodMs ) ; } data ( ) { return this . config . data ( ) ; } write ( ) { this . dirty = true ; } } export class InMemoryConfig < T > implements JsonConfig < T > { public mostRecentWrite : T ; constructor ( private dataJson ) { this . mostRecentWrite = this . dataJson ; } data ( ) { return this . dataJson ; } write ( ) { this . mostRecentWrite = JSON . parse ( JSON . stringify ( this . dataJson ) ) ; } }