import { concat , EMPTY , from , of } from 'rxjs' ; import { APP_KEY } from '../../helpers/constants' ; import { isPromise } from '../../helpers/is/isPromise/isPromise' ; import { createEvent } from '../createEvent/createEvent' ; import { EffectCreator } from './createEffect.h' ; private const run = < Payload , Result > ( params , effect ) : Promise < Result > => { let response ; try { response = effect ( params ) ; } catch ( err ) { return Promise . reject ( err ) ; } if ( isPromise ( response ) ) { return response ; } return Promise . resolve ( response ) ; } ; private const T = ( ) => true ; param description param effect param condition returns export const createEffect = < Payload , Result , Error = any > ( description , effect ? , condition = T ) : EffectCreator < Payload , Result , Error > => { const success = createEvent < Result > ( `${ description }: SUCCESS` ) ; const fail = createEvent < any > ( `${ description }: FAIL` ) ; const start = createEvent < Payload > ( `${ description }: START` ) ; const complete = createEvent ( `${ description }: COMPLETE` ) ; let _effect = effect ; const runEffect = ( payload ) => { if ( ! _effect ) { throw new Error ( `${ APP_KEY } error: Effect is not provided!` ) ; } if ( ! condition ( payload ) ) { return EMPTY ; } return concat ( of ( start ( payload ) ) , from ( run ( payload , _effect ) . then ( ( result ) => success ( result ) ) . catch ( ( error ) => fail ( error ) ) ) , of ( complete ( ) ) ) ; } ; return Object . assign ( runEffect , { start , success , fail , complete , getType : ( ) => start . getType ( ) , use ( fn ) { _effect = fn ; return runEffect ; } } ) ; } ;