import { computed } from '@vue/composition-api' ; import { Context , sharedRef , Logger , configureFactoryParams , FactoryParams , } from '@vue-storefront/core' ; import { ComposableFunctionArgs , PlatformApi } from '@vue-storefront/core/lib/src/types' ; import { UseStore } from '../types/composables' ; export interface UseStoreFactoryParams < STORES , STORE , API extends PlatformApi = any > extends FactoryParams < API > { load : ( context : Context , params ? : ComposableFunctionArgs < { } > ) => Promise < STORES > ; change : ( context : Context , params : ComposableFunctionArgs < STORE > ) => void ; } export function useStoreFactory < STORES , STORE , API extends PlatformApi = any > ( factoryParams ) { return function useStore ( cacheId = '' ) : UseStore < STORES , STORE , API > { const ssrKey = cacheId || 'useStoreFactory' ; const stores = sharedRef < STORES > ( [ ] , `${ ssrKey }-stores` ) ; const loading = sharedRef < boolean > ( false , `${ ssrKey }-loading` ) ; const _factoryParams = configureFactoryParams ( factoryParams ) ; const load = async ( params ? ) => { Logger . debug ( `useStore/${ ssrKey }/load` ) ; loading . value = true ; try { stores . value = await _factoryParams . load ( params ) ; } finally { loading . value = false ; } } ; const change = async ( store ) : Promise < void > => { loading . value = true ; try { await _factoryParams . change ( store ) ; } finally { loading . value = false ; } } ; return { load , change , stores : computed ( ( ) => stores . value ) , loading : computed ( ( ) => loading . value ) , } ; } ; }