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 · 0 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

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

1 participant