import { RPCMethod } from '../net' ; import { Matcher , ReqMiddlewareFn , ResMiddlewareFn } from '../util' ; const enum MiddlewareType { REQ , RES } export class BaseProvider { middleware = { request : { use : < I , O > ( fn , match = '*' ) => { this . pushMiddleware < MiddlewareType . REQ > ( fn , MiddlewareType . REQ , match ) ; } , } , response : { use : < I , O , E > ( fn , match = '*' ) => { this . pushMiddleware < MiddlewareType . RES > ( fn , MiddlewareType . RES , match ) ; } , } , } ; protected nodeURL : string ; protected reqMiddleware : Map < Matcher , ReqMiddlewareFn [ ] > ; protected resMiddleware : Map < Matcher , ResMiddlewareFn [ ] > ; constructor ( nodeURL , reqMiddleware = new Map ( ) , resMiddleware = new Map ( ) ) { this . nodeURL = nodeURL ; this . reqMiddleware = reqMiddleware ; this . resMiddleware = resMiddleware ; } param { ResMiddlewareFn } param { T } type param { Matcher } match returns { void } protected pushMiddleware < T extends MiddlewareType > ( fn , type , match ) { if ( type !== MiddlewareType . REQ && type !== MiddlewareType . RES ) { throw new Error ( 'Please specify the type of middleware being added' ) ; } if ( type === MiddlewareType . REQ ) { const current = this . reqMiddleware . get ( match ) || [ ] ; this . reqMiddleware . set ( match , [ ... current , < ReqMiddlewareFn > fn ] ) ; } else { const current = this . resMiddleware . get ( match ) || [ ] ; this . resMiddleware . set ( match , [ ... current , < ResMiddlewareFn > fn ] ) ; } } param { Matcher } match returns { [ ReqMiddlewareFn [ ] , ResMiddlewareFn [ ] ] } protected getMiddleware ( method ) { const reqFns = [ ] ; const resFns = [ ] ; for ( const [ key , transformers ] of this . reqMiddleware . entries ( ) ) { if ( typeof key === 'string' && key !== '*' && key === method ) { reqFns . push ( ... transformers ) ; } if ( key instanceof RegExp && key . test ( method ) ) { reqFns . push ( ... transformers ) ; } if ( key === '*' ) { reqFns . push ( ... transformers ) ; } } for ( const [ key , transformers ] of this . resMiddleware . entries ( ) ) { if ( typeof key === 'string' && key !== '*' && key === method ) { resFns . push ( ... transformers ) ; } if ( key instanceof RegExp && key . test ( method ) ) { resFns . push ( ... transformers ) ; } if ( key === '*' ) { resFns . push ( ... transformers ) ; } } return [ reqFns , resFns ] ; } }