import { AxiosError , default as axios } from "axios" ; import { compose , withHandlers , withState } from "recompose" ; import { withNotification , WithNotificationDispatch , withSession , WithSessionState } from "enhancers" ; import { NotificationType } from "providers/store/notification" ; /**
 * Form submission enhancer options
 */ export interface WithFormSubmitOptions { target ? : string ; message ? : string ; authorize ? : boolean ; } template TResponse interface State < TResponse > { pending : boolean ; success : boolean ; response ? : TResponse ; err ? : AxiosError ; } template TResponse interface StateProps < TResponse > { form : Readonly < State < TResponse > > ; setForm : ( form : State < TResponse > ) => Readonly < State < TResponse > > ; } template TRequest interface HandlerProps < TRequest extends { } > { submit : ( request ? : TRequest ) => Promise < void > ; } template TResponse type HandlerCallbackProps < TResponse = void > = WithNotificationDispatch & WithSessionState & StateProps < TResponse > ; template TRequest template TResponse export type WithFormSubmit < TRequest extends { } = any , TResponse = void > = StateProps < TResponse > & HandlerProps < TRequest > ; template TRequest template TResponse param options return export const withFormSubmit = < TRequest extends { } , TResponse = void > ( { target , message , authorize } = { } ) => compose < WithFormSubmit < TRequest , TResponse > , { } > ( withNotification ( ) , withSession ( ) , withState ( "form" , "setForm" , ( ) : State < TResponse > => ( { pending : false , success : false } ) ) , withHandlers < HandlerCallbackProps < TResponse > , HandlerProps < TRequest > > ( { submit : ( { setForm , displayNotification , dismissNotification , session } ) => async ( request ) => { const url = `/${ window . env . API_BASE_PATH }/${ ( target || location . pathname ) . replace ( /^\// , "" ) }` ; setForm ( { pending : true , success : false } ) ; try { dismissNotification ( ) ; const { data : response } = await axios . post < TResponse > ( url , request || { } , { withCredentials : true , headers : { "Content-Type" : "application/json" , ... ( authorize && session ? { Authorization : `Bearer ${ session . access . token }` } : { } ) } } ) ; setForm ( { pending : false , success : true , response } ) ; if ( message ) { displayNotification ( { type : NotificationType . SUCCESS , message } ) ; } } catch ( err ) { const { response } = err ; if ( response ) { displayNotification ( { type : NotificationType . ERROR , message : response . data . message } ) ; } setForm ( { pending : false , success : false , err } ) ; } } } ) ) ;