import nothing from '@tinkoff/utils/function/nothing' ; import { Plugin , Status , ContextState } from '@tinkoff/request-core' ; import { VALIDATE } from './constants' ; interface Validator { ( state ) : any ; } interface Options { allowFallback ? : boolean ; validator ? : Validator ; errorValidator ? : Validator ; } param { function } validator param { function } errorValidator param { boolean } allowFallback return { { complete : complete } } export default ( { validator = nothing , allowFallback = true , errorValidator = nothing } = { } ) : Plugin => ( { complete : ( context , next ) => { const state = context . getState ( ) ; const { request } = state ; const error = validator ( state ) ; context . updateExternalMeta ( VALIDATE , { validated : ! error , } ) ; if ( error ) { return next ( { error , request : allowFallback ? request : { ... request , fallbackCache : false , } , status : Status . ERROR , } ) ; } return next ( ) ; } , error : ( context , next ) => { const state = context . getState ( ) ; const isSuccess = errorValidator ( state ) ; context . updateExternalMeta ( VALIDATE , { errorValidated : ! ! isSuccess , } ) ; if ( isSuccess ) { context . updateExternalMeta ( VALIDATE , { error : state . error , } ) ; return next ( { error : null , status : Status . COMPLETE , } ) ; } return next ( ) ; } , } ) ;