import Operation from "../artifacts/operation" ; import Specifications from "../artifacts/specifications" ; import Context from "../Context" ; import OperationMismatchError from "../errors/OperationMismatchError" ; import getHandlerByOperation from "../handlers/handlerMappers" ; import IHandlers from "../handlers/IHandlers" ; import { NextFunction } from "../MiddlewareFactory" ; import ILogger from "../utils/ILogger" ; export class export default class HandlerMiddlewareFactory { param { IHandlers } handlers param { ILogger } logger memberof constructor ( private readonly handlers , private readonly logger ) { } memberof public createHandlerMiddleware ( ) { return ( context , next ) => { this . logger . info ( `HandlerMiddleware: DeserializedParameters=${ JSON . stringify ( context . handlerParameters , ( key , value ) => { if ( key === "body" ) { return "ReadableStream" ; } return value ; } ) }` , context . contextID ) ; if ( context . operation === undefined ) { const handlerError = new OperationMismatchError ( ) ; this . logger . error ( `HandlerMiddleware: ${ handlerError . message }` , context . contextID ) ; return next ( handlerError ) ; } if ( Specifications [ context . operation ] === undefined ) { this . logger . warn ( `HandlerMiddleware: cannot find handler for operation ${ Operation [ context . operation ] }` ) ; } const handlerPath = getHandlerByOperation ( context . operation ) ! ; const args = [ ] ; for ( const arg of handlerPath . arguments ) { args . push ( context . handlerParameters ! [ arg ] ) ; } args . push ( context ) ; const handler = ( this . handlers as any ) [ handlerPath . handler ] ; const handlerMethod = handler [ handlerPath . method ] as ( ) => Promise < any > ; handlerMethod . apply ( handler , args as any ) . then ( ( response ) => { context . handlerResponses = response ; } ) . then ( next ) . catch ( next ) ; } ; } }