import createStore from 'unistore' ; import { IgApiClient } from 'instagram-private-api' ; import { Observable } from 'rxjs' ; import { publishReplay , pluck , distinctUntilChanged , } from 'rxjs/operators' ; import { Config } from './config' ; interface State { imageLikes : number ; serverCalls : number ; config : Config ; client : IgApiClient ; } type changeFunction = ( state : State ) => Partial < State > ; interface UniStoreObservable extends Observable < State > { setState : ( state : Partial < State > , overwrite ? : boolean ) => void ; getState : ( ) => State ; connect : ( ) => void ; change : ( fn : changeFunction ) => void ; pluck : ( key : string ) => Observable < any > ; } const org_store = createStore ( ) ; const store = Observable . create ( ( observer ) => { org_store . subscribe ( ( state ) => { observer . next ( state ) ; } ) ; } ) . pipe ( publishReplay ( 1 ) ) ; store . connect ( ) ; store . setState = ( newState ) : void => org_store . setState ( newState ) ; store . getState = ( ) : State => org_store . getState ( ) as State ; store . change = ( fn ) : void => org_store . setState ( fn ( org_store . getState ( ) as State ) ) ; store . pluck = ( key ) : Observable < any > => store . pipe ( pluck ( key ) , distinctUntilChanged ( ) ) ; const initState = { imageLikes : 0 , serverCalls : 0 , } ; store . setState ( initState ) ; const addServerCalls = ( amount = 1 ) : void => store . change ( ( { serverCalls } ) => ( { serverCalls : serverCalls + amount } ) ) ; export { store , State , UniStoreObservable , addServerCalls , } ;