| 67 | * ``` |
| 68 | */ |
| 69 | export class DefaultSequence implements SequenceHandler { |
| 70 | /** |
| 71 | * Optional invoker for registered middleware in a chain. |
| 72 | * To be injected via SequenceActions.INVOKE_MIDDLEWARE. |
| 73 | */ |
| 74 | @inject(SequenceActions.INVOKE_MIDDLEWARE, {optional: true}) |
| 75 | protected invokeMiddleware: InvokeMiddleware = () => false; |
| 76 | |
| 77 | /** |
| 78 | * Constructor: Injects findRoute, invokeMethod & logError |
| 79 | * methods as promises. |
| 80 | * |
| 81 | * @param findRoute - Finds the appropriate controller method, |
| 82 | * spec and args for invocation (injected via SequenceActions.FIND_ROUTE). |
| 83 | * @param parseParams - The parameter parsing function (injected |
| 84 | * via SequenceActions.PARSE_PARAMS). |
| 85 | * @param invoke - Invokes the method specified by the route |
| 86 | * (injected via SequenceActions.INVOKE_METHOD). |
| 87 | * @param send - The action to merge the invoke result with the response |
| 88 | * (injected via SequenceActions.SEND) |
| 89 | * @param reject - The action to take if the invoke returns a rejected |
| 90 | * promise result (injected via SequenceActions.REJECT). |
| 91 | */ |
| 92 | constructor( |
| 93 | @inject(SequenceActions.FIND_ROUTE) protected findRoute: FindRoute, |
| 94 | @inject(SequenceActions.PARSE_PARAMS) protected parseParams: ParseParams, |
| 95 | @inject(SequenceActions.INVOKE_METHOD) protected invoke: InvokeMethod, |
| 96 | @inject(SequenceActions.SEND) public send: Send, |
| 97 | @inject(SequenceActions.REJECT) public reject: Reject, |
| 98 | ) {} |
| 99 | |
| 100 | /** |
| 101 | * Runs the default sequence. Given a handler context (request and response), |
| 102 | * running the sequence will produce a response or an error. |
| 103 | * |
| 104 | * Default sequence executes these steps |
| 105 | * - Executes middleware for CORS, OpenAPI spec endpoints |
| 106 | * - Finds the appropriate controller method, swagger spec |
| 107 | * and args for invocation |
| 108 | * - Parses HTTP request to get API argument list |
| 109 | * - Invokes the API which is defined in the Application Controller |
| 110 | * - Writes the result from API into the HTTP response |
| 111 | * - Error is caught and logged using 'logError' if any of the above steps |
| 112 | * in the sequence fails with an error. |
| 113 | * |
| 114 | * @param context - The request context: HTTP request and response objects, |
| 115 | * per-request IoC container and more. |
| 116 | */ |
| 117 | async handle(context: RequestContext): Promise<void> { |
| 118 | try { |
| 119 | const {request, response} = context; |
| 120 | // Invoke registered Express middleware |
| 121 | const finished = await this.invokeMiddleware(context); |
| 122 | if (finished) { |
| 123 | // The response been produced by the middleware chain |
| 124 | return; |
| 125 | } |
| 126 | const route = this.findRoute(request); |