-
Notifications
You must be signed in to change notification settings - Fork 402
Description
I was trying to:
I'm currently adding routing-controllers to an existing application and am in the progress of a progressive migration of endpoints.
The problem:
Recently I've noticed that one of my middleware functions that is attached to the express server (outside of a routing-controllers Controller) appears to be invoked after some of the endpoints (defined within a Controller) are hit but not others.
The endpoints that continue down the middleware chain contain path parameters and the endpoints that don't appear to be terminal.
Any ideas why this behaviour might occur? It seems strange that the behaviour isn't consistent for all endpoints reached.
Example to replicate:
Using the below code example and sending a request to /test/fixed
results in the following being logged:
test fixed
However sending a request to /test/path
results in the following being logged:
test path
someMiddlewareFunction invoked!
Ideally either both requests trigger the someMiddlewareFunction
middleware function or both of them don't; but at the moment I'm just curious to know why there might be a difference between the two?
import 'reflect-metadata'
import http from 'http'
import express, { Request, Response } from 'express'
import { Get, JsonController, Param, Req, Res, useExpressServer } from 'routing-controllers'
@JsonController()
class MyController {
@Get('/test/fixed')
async testA(@Req() req: Request, @Res() res: Response) {
console.log('test fixed')
return 'test/fixed'
}
@Get('/test/:path')
async testB(@Param('path') path: string, @Req() req: Request, @Res() res: Response) {
console.log('test path')
return 'test/:path'
}
}
const app = express()
useExpressServer(app, {
controllers: [MyController],
defaultErrorHandler: false,
classTransformer: false,
})
app.use(someMiddlewareFunction)
app.use(errorHandler)
http.createServer(app).listen(9000, () => {
console.log(`Welcome!`)
})
function someMiddlewareFunction(req: Request, res: Response, next: Function) {
console.log('someMiddlewareFunction invoked!')
next()
}
function errorHandler(error: any, req: Request, res: Response, next: Function) {
// do stuff like set response status codes, headers and content based on error shapes
if (!res.headersSent) {
res.status(error.httpCode || 500).send(error.message || 'Internal server error')
}
next(error)
}