import { Store , Getter , Action , Payload } from 'vuex' ; import { Dictionary , LocalModule , LocalGetter , LocalAction } from './declarations' ; import { localKey , mapValues , mapKeys } from './utils' ; export function registerLocalModule ( store , modulePath , module ) { const { state , getters = { } , actions = { } , mutations = { } } = module ; const name = modulePath [ modulePath . length - 1 ] ; store . registerModule ( modulePath , { state , getters : mapLocalKeys ( mapLocalGetters ( getters , name ) , name ) , actions : mapLocalKeys ( mapLocalActions ( actions , getters , name ) , name ) , mutations : mapLocalKeys ( mutations , name ) } ) ; } export function unregisterLocalModule ( store , modulePath ) { store . unregisterModule ( modulePath ) ; } export function mapLocalKeys ( obj , moduleName ) { return mapKeys ( obj , ( _ , key ) => localKey ( key , moduleName ) ) ; } function mapLocalGetters ( getters , moduleName ) { return mapValues ( getters , getter => { return function wrappedGetter ( state , rootGetters , rootState ) { const localGetters = makeLocalGetters ( Object . keys ( getters ) , rootGetters , moduleName ) ; return getter ( state , localGetters , rootState , rootGetters ) ; } as Getter < any , any > ; } ) ; } function mapLocalActions ( actions , getters , moduleName ) { return mapValues ( actions , action => { return function wrappedAction ( context , payload ) { const { commit , dispatch } = context ; context . commit = function localCommit ( type , payload ? , options = { } ) { if ( typeof type === 'object' ) { options = payload ; type = type . type ; payload = type ; } return commit ( options . root ? type : localKey ( type , moduleName ) , payload , options ) ; } ; context . dispatch = function localDispatch ( type , payload ? , options = { } ) { if ( typeof type === 'object' ) { options = payload ; type = type . type ; payload = type ; } return dispatch ( options . root ? type : localKey ( type , moduleName ) , payload , options ) ; } ; const rootGetters = context . getters ; context . rootGetters = rootGetters ; context . getters = makeLocalGetters ( Object . keys ( getters ) , rootGetters , moduleName ) ; action ( context , payload ) ; } as LocalAction < any , any > ; } ) ; } function makeLocalGetters ( getterKeys , getters , moduleName ) { const localGetters = { } ; getterKeys . forEach ( key => { Object . defineProperty ( localGetters , key , { get ( ) { return getters [ localKey ( key , moduleName ) ] ; } } ) ; } ) ; return localGetters ; }