import merge from 'lodash.merge' ; import clonedeep from 'lodash.clonedeep' ; import set from 'lodash.set' ; import compareVersions from 'compare-versions' ; import axios from 'axios' ; import fs from 'fs-extra' ; import path from 'path' ; import { IConfig } from './interface' ; class ConfigStore { config : IConfig ; remoteConfigPath : string = path . resolve ( __dirname , './remote-config.json' ) ; runTimeConfigPath : string = path . resolve ( ) ; set ( keyPath , value ) { set ( this . config , keyPath , value ) ; return this . config ; } getConfig ( ) { return clonedeep ( this . config ) ; } init ( defaultConfig ) { const remoteConfig = this . getSavedRemoteConfig ( ) as IConfig ; const localConfig = this . getLocalConfig ( defaultConfig . virtualPath . configPath ) as IConfig ; this . config = merge ( { } , defaultConfig , remoteConfig , localConfig ) ; this . remoteConfigOperation ( ) ; return this ; } async remoteConfigOperation ( ) { const { remoteConfigUrl , version } = this . config ; if ( ! remoteConfigUrl ) { return ; } try { const res = await axios . get ( remoteConfigUrl ) ; const remoteConfigJSON = res . data ; if ( compareVersions . compare ( version , remoteConfigJSON . version , '>' ) ) { return ; } await fs . writeJson ( this . remoteConfigPath , remoteConfigJSON ) ; } catch ( e ) { } } getSavedRemoteConfig = ( ) => { try { return require ( this . remoteConfigPath ) ; } catch ( e ) { return { } ; } } ; getLocalConfig = ( localConfigPath ) => { try { return require ( localConfigPath ) ; } catch ( e ) { return { } ; } } ; } export default new ConfigStore ( ) ;