Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to execute server-level middleware after response is sent using InversifyExpressServer #1704

Open
2 of 4 tasks
madmatah opened this issue Jan 14, 2025 · 3 comments
Open
2 of 4 tasks

Comments

@madmatah
Copy link

madmatah commented Jan 14, 2025

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

I would like to run some server-level middlewares (that are not error handlers) after the HTTP response has been sent.

For example, I want to log all status codes returned by my server:

const statusCodeLoggerMiddleware = (req, res, next) => {
  console.log(`STATUS: ${res.statusCode}`);
  next();
};

@controller('/test')
export class TestController extends BaseHttpController {
  @httpGet('/success') public getSuccess() {
    return 'OK';
  }

  @httpGet('/teapot') public getTeapot() {
    return this.statusCode(418);
  }
}

const container = new Container();
const server = new InversifyExpressServer(container);

server.setErrorConfig((app) => {
  app.use(statusCodeLoggerMiddleware);
});

const app = server.build();

I used setErrorConfig() method to register my middleware after the controller routes.
But it is never executed.

Did I miss something to get the expected result?

Steps to reproduce

No response

Expected behavior

I expect middlewares registered after the controller routes to be executed.
In the current state, only error handlers are executed.

Possible solution

I think the handlerFactory() method in InversifyExpressServer should call next() after the response is sent:

private handlerFactory(
        controllerName: string,
        key: string,
        parameterMetadata: ParameterMetadata[]
    ): RequestHandler {
        return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
            try {
                 [...]
                 next();
            } catch (err) {
                next(err);
            }
        };
    }

I can make a PR if this solution is OK for you.

Package version

6.2.1

Node.js version

20.11.1

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Stack trace

No response

Other

inversify-express-utils version 6.4.10

@notaphplover
Copy link
Member

Hey @madmatah, setErrorConfig sets the handler to be executed as a fallback in case the request handler fails, consider using @withMiddleware instead. I tested it locally and worked like a charm:

const statusCodeLoggerMiddleware = (req, res, next) => {
  console.log(`STATUS: ${res.statusCode}`);
  next();
};

@controller('/test')
@withMiddleware(statusCodeLoggerMiddleware)
export class TestController extends BaseHttpController {
  @httpGet('/success') public getSuccess() {
    return 'OK';
  }

  @httpGet('/teapot') public getTeapot() {
    return this.statusCode(418);
  }
}

const container = new Container();
const server = new InversifyExpressServer(container);

const app = server.build();

I'll close the issue, but we can keep discussing it if you have any doubt.

@madmatah
Copy link
Author

madmatah commented Jan 31, 2025

Hello @notaphplover and thank you for your reply!

The example that you gave using @withMiddleware does not work as expected :
When I make a HTTP request GET /test/teapot I get a response with status code 418. But the middleware logs STATUS: 200 instead of STATUS: 418.

And that's because the middleware is registered for execution before my controller code.

The main point of this issue is that I want to be able to run middleware after the response has been sent. I've taken a simple example here to illustrate my problem, but a more realistic example would be to create middleware that collects statistics on the response time of all my routes.

I can do it easily with express, but I'm stuck to do it with InversifyExpressServer.

And the second point is that I'm looking for a way to declare this kind of middleware on a server-level, to execute it everytime. I don't want to decorate all my controllers for this use case. The setConfig() method allows to declare "server level middlewares" that are executed before the controller, and I'm looking for a way to register middlewares after the response has been sent. That's why i mentionned setErrorConfig(), but i'm aware that it's not it's original purpose.

@notaphplover
Copy link
Member

Hey @madmatah , I see. being totally honest I thought when a middleware ends the request response cycle, the next middleware should not be invoked, but after having a look at the docs it's not forbidden.

I'm reopening the issue now

@notaphplover notaphplover reopened this Jan 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants