import { all , and , equals , isArray , isNumber , isObject , isString , or } from '@typed/logic' ; import { hasOwnProperty } from '@typed/objects' ; import { JsonRpcFailedResponse , JsonRpcResponse , JsonRpcSuccessfulResponse } from '../../model' ; const REQUIRED_KEYS = [ 'jsonrpc' , 'id' ] ; const OPTIONAL_KEYS = [ 'result' , 'error' ] ; const VALIDATE_RESPONSE_VALUES = { jsonrpc : and ( isString , equals ( '2.0' ) ) , id : or ( isString , isNumber ) , result : or ( isArray , isObject ) , error : or ( isString , isNumber ) , } ; export const isSuccessfulResponse = ( x ) : x is JsonRpcSuccessfulResponse => isResponse ( x ) && hasOwnProperty ( 'result' , x ) ; export const isFailedResponse = ( x ) : x is JsonRpcFailedResponse => isResponse ( x ) && hasOwnProperty ( 'error' , x ) ; export function isResponse ( x ) { if ( ! isObject ( x ) ) { return false ; } const hasPropertyAndIsValid = ( key ) => hasOwnProperty ( key , x ) && VALIDATE_RESPONSE_VALUES [ key ] ( x [ key ] ) ; if ( ! all ( hasPropertyAndIsValid , REQUIRED_KEYS ) ) { return false ; } return OPTIONAL_KEYS . reduce ( ( valid , key ) => ( valid ? hasPropertyAndIsValid ( key ) : false ) , true as boolean ) ; }