white-label
white-label copied to clipboard
Using the same controller for multiple requests
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);
+ }
)