import * as AsyncLock from "async-lock" ; import * as debug from "debug" ; import * as fs from "fs" ; import * as _ from "lodash" ; import * as path from "path" ; import { IMindConnectConfiguration } from ".." ; const log = debug ( "mindconnect-storage" ) ; export interface export interface IConfigurationStorage { GetConfig ( config ) : IMindConnectConfiguration ; SaveConfig ( config ) : Promise < IMindConnectConfiguration > ; } export function IsConfigurationStorage ( arg ) { return arg . GetConfig !== undefined && arg . SaveConfig !== undefined ; } export class export class DefaultStorage implements IConfigurationStorage { private lock : AsyncLock ; public GetConfig ( configuration ) { try { const jsonString = fs . readFileSync ( path . resolve ( `${ this . _basePath }/${ configuration . content . clientId }.json` ) ) ; const json = JSON . parse ( jsonString . toString ( ) ) as IMindConnectConfiguration ; if ( _ . isEqual ( json . content , configuration . content ) ) { return json ; } else { log ( "The configuration has changed we will onboard again." ) ; } } catch ( err ) { log ( `There is no configuration stored yet for agent with id ${ configuration . content . clientId }` ) ; } return configuration ; } public async SaveConfig ( config ) { const fileName = `${ this . _basePath }/${ config . content . clientId }.json` ; return await this . lock . acquire ( fileName , ( ) => { const data = JSON . stringify ( config ) ; fs . writeFileSync ( fileName , data ) ; return config ; } ) ; } constructor ( private _basePath ) { if ( ! fs . existsSync ( this . _basePath ) ) { fs . mkdirSync ( this . _basePath ) ; } this . lock = new AsyncLock ( { } ) ; } }