import { computed } from '@vue/composition-api' ; import { configureFactoryParams , Context , FactoryParams , Logger , sharedRef , } from '@vue-storefront/core' ; import { ComposableFunctionArgs , PlatformApi } from '@vue-storefront/core/lib/src/types' ; import { UseCategorySearch , UseCategorySearchErrors } from '../types/composables' ; export interface UseCategorySearchFactory < CATEGORY , CATEGORY_SEARCH_PARAMS , API extends PlatformApi = any > extends FactoryParams < API > { search : ( context : Context , params : ComposableFunctionArgs < CATEGORY_SEARCH_PARAMS > ) => Promise < CATEGORY [ ] > ; } export function useCategorySearchFactory < CATEGORY , CATEGORY_SEARCH_PARAMS , API extends PlatformApi = any > ( factoryParams ) { return function useCategorySearch ( id = '' ) : UseCategorySearch < CATEGORY , CATEGORY_SEARCH_PARAMS , API > { const ssrKey = id || 'useCategorySearch' ; const result = sharedRef < CATEGORY > ( [ ] , `${ ssrKey }-result` ) ; const loading = sharedRef ( false , `${ ssrKey }-loading` ) ; const error = sharedRef < UseCategorySearchErrors > ( { search : null , } , `${ ssrKey }-error` ) ; const _factoryParams = configureFactoryParams ( factoryParams ) ; const search = async ( params ) : Promise < CATEGORY [ ] > => { Logger . debug ( `useCategorySearch/${ ssrKey }/search` ) ; try { loading . value = true ; const data = await _factoryParams . search ( params ) ; result . value = data ; error . value . search = null ; return data ; } catch ( err ) { error . value . search = err ; Logger . error ( `useCategorySearch/${ ssrKey }/search` , err ) ; } finally { loading . value = false ; } } ; return { search , result : computed ( ( ) => result . value ) , loading : computed ( ( ) => loading . value ) , error : computed ( ( ) => error . value ) , } ; } ; }