Write express controllers like a pro
Yeah I know these are not express controllers they are Nintendo’s 😅. But If you are bored writing the express controllers the boring way I will share with you a better solution today.
The old way
Let’s suppose you have some endpoints related /cars, /bike, etc. And for each of their controller, you wanna define some middleware’s related GET, UPDATE, PATCH, and DELETE requests. Let’s say you are defining the update middleware first like bellow
catchAysync
in the above function is just to wrap the function in try-catch
block due to the use of async-await
. And the AppError
is just custom designed error to be passed to the global error controller by doing next(error)
.And for the /cars endpoint you are repeating the same code.
So when your app will be growing large it becomes difficult to write the same middleware code for the GET, UPDATE, PATCH, and DELETE functionality, for all the endpoints. There is a better way for defining your code.
Handler Factory.js
You just need to define a controller module once and it will save you from rewriting your code. You can simply change the above two blocks of code to bellow
Do the same with bikeController
module
You can do the same with all the other CRUD operations as shown.
See by just using the factory
object we save our time and solve the boilerplate. You just need to implement this hadlerFactory.js
module.
Implementing Handler Factory
Implementing this module is similar like implementing the basic controller. You just have to define the controller as a general controller that can be used with your other controllers.
You just have to pass the mongoose Model
to the method and it will create a new object in the DB using that model. Similarly, you can write your whole handler.
So now you can use this factory module while building your other controller.
AppError
. or simply pass some message string and throw an error. You can refer to the bellow code if you wanna implement the AppError
module that makes passing errors to the express global error controller easy by just passing the error message and status code as a parameter i.e. next(new AppError(”my error message”, 404))
.Acknowledgement
- This node.js course helped me implement the above code node.js bootcamp
Комментарии