import { Ref , computed } from '@vue/composition-api' ; import { ComposableFunctionArgs , configureFactoryParams , Context , FactoryParams , Logger , sharedRef , } from '@vue-storefront/core' ; import { PlatformApi } from '@vue-storefront/core/lib/src/types' ; import { UsePaymentProvider , UsePaymentProviderErrors } from '../types/composables' ; export interface UsePaymentProviderParams < STATE , PAYMENT_METHOD , API extends PlatformApi = any > extends FactoryParams < API > { load : ( context : Context , params ? : ComposableFunctionArgs < { } > ) => Promise < STATE > ; save : ( context : Context , params : ComposableFunctionArgs < { paymentMethod : PAYMENT_METHOD ; } > ) => Promise < STATE > ; } export const usePaymentProviderFactory = < STATE , PAYMENT_METHOD , API extends PlatformApi = any > ( factoryParams ) => function usePaymentProvider ( ) : UsePaymentProvider < STATE , PAYMENT_METHOD , API > { const loading = sharedRef ( false , 'usePaymentProvider-loading' ) ; const state = sharedRef ( null , 'usePaymentProvider-response' ) ; const _factoryParams = configureFactoryParams ( factoryParams ) ; const error = sharedRef ( { load : null , save : null , } , 'usePaymentProvider-error' ) ; const setState = ( newState ) => { state . value = newState ; Logger . debug ( 'usePaymentProvider.setState' , newState ) ; } ; const save = async ( params ) => { Logger . debug ( 'usePaymentProvider.save' ) ; try { loading . value = true ; state . value = await _factoryParams . save ( { paymentMethod : params . paymentMethod || { } , customQuery : params ?. customQuery || { } , state , } ) ; error . value . save = null ; } catch ( err ) { error . value . save = err ; Logger . error ( 'usePaymentProvider/save' , err ) ; } finally { loading . value = false ; } } ; const load = async ( params ? ) => { Logger . debug ( 'usePaymentProvider.load' ) ; try { loading . value = true ; state . value = await _factoryParams . load ( { customQuery : params ?. customQuery || { } , state , } ) ; error . value . load = null ; } catch ( err ) { error . value . load = err ; Logger . error ( 'usePaymentProvider/load' , err ) ; } finally { loading . value = false ; } } ; return { state , loading : computed ( ( ) => loading . value ) , error : computed ( ( ) => error . value ) , load , save , setState , } ; } ;