Skip to content

Using the same controller for multiple requests #17

@move-zig

Description

@move-zig

It seems like you create a singleton for each controller and use a controller's execute method as a handler for express routes. BaseController.execute is synchronous, but it calls the sub-class's executeImpl method, which might be asynchronous. executeImpl might call BaseController.conflict, BaseController.fail, etc. which rely on BaseController.req and BaseController.res.

If multiple requests to the same endpoint come in faster than they can be handled, the multiple calls to execute will overwrite the req and res fields. Then when the executeImpl method finally calls this.conflict, won't it be using the wrong res for res.send?

Instead, should we not create a new controller each time we want to handle a route?

E.g.,

- import { createUserController } from '../../../useCases/createUser';
+ import { CreateUserController } from '../../../useCases/createUser/CreateUserController';
+ import { createUserUseCase } from '../../../useCases/createUser'; // export the use case singleton in this file

const userRouter = express.Router();

userRouter.post('/',
-   (req, res) => createUserController.execute(req, res)
+   (req, res) => {
+     const controller = new CreateUserController(createUserUseCase);
+     controller.execute(req, res);
+   }
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions