Using expressJS 4.X with nodeJS 6.x
I was previously defining my routes this way :
/**
* @api {get} /users/:userId Get a user
* @apiName GetUser
* @apiGroup User
*
* @apiParam {Integer} userId Users unique ID.
*
* @apiSuccess (Success 201) {text} User email
* @apiError {text} 401/Unauthorized.
* @apiError {text} 404/Not Foud Unknown userId
*/
router.get('/users/:userId', function(req, res, next) {
const userId = req.params.userId;
//get user
res.json(user);
}
I found it was the correct way to do it because :
- You write the route documentation above the route definition
- If you modify the route, you modify the documentation
- You have the route documentation above your controller
- URL params/body content (req.params.name // req.body.name)
- HTTP Error code to return
- IDE like webstorm use those comment for autocompletion
Looking for best practices, I've been told many times I should create a Controller and make the route defintion elsewhere, ending with the following code :
class UserController {
constructor() {
this.listAll = this.listAll.bind(this);
}
getUser(req, res, next) {
const userId = req.params.userId;
//get user...
res.json(user);
}
}
router.get('/users/, UserController.getUser);
The only good reason I see with this way of organising your code is that if you have 2 roads doing the same stuff, you can make them use the same controller.
- Should I keep seperating my controller & my routes ?
- If yes, how should I document it ?
- What are the benefits of such a code organisation ?