white-label icon indicating copy to clipboard operation
white-label copied to clipboard

Using the same controller for multiple requests

Open move-zig opened this issue 4 years ago • 0 comments

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);
+   }
)

move-zig avatar May 26 '21 14:05 move-zig