import { autorun , ObservableMap , set , toJS } from 'mobx' ; import { injectable } from '@cloudbeaver/core-di' ; let id = 0 ; @ injectable ( ) export class LocalStorageSaveService { withAutoSave < T > ( store , name ? , remap ? ) { let firstRun = true ; const storeId = name || ++ id ; autorun ( ( ) => { if ( firstRun ) { const state = localStorage . getItem ( `${ storeId }` ) ; if ( state ) { try { const parsed = this . parseData ( store , state , remap ) ; set ( store , parsed ) ; } catch ( e ) { console . log ( 'Error when parsing local storage value' , e ) ; } } firstRun = false ; } localStorage . setItem ( `${ storeId }` , this . stringifyData ( store ) ) ; } ) ; } private parseData ( store , data , remap ? ) { if ( store instanceof ObservableMap ) { data = this . parseMap ( data ) ; } else { data = JSON . parse ( data ) ; } if ( remap ) { data = remap ( data ) ; } if ( store instanceof ObservableMap ) { data = Array . from ( ( data as Map < any , any > ) . entries ( ) ) . reduce < { [ key ] : any ; } > ( ( obj , [ key , value ] ) => { obj [ key ] = value ; return obj ; } , { } ) ; } return data ; } private stringifyData ( store ) { if ( store instanceof ObservableMap ) { return this . stringifyMap ( toJS ( store ) ) ; } return JSON . stringify ( toJS ( store ) ) ; } private stringifyMap ( map ) { return JSON . stringify ( Array . from ( map . entries ( ) ) ) ; } private parseMap ( data ) { return new Map ( JSON . parse ( data ) ) ; } }