2

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 ?
IggY
  • 3,005
  • 4
  • 29
  • 54

1 Answers1

1

Bit of a philosophical question which should be asked rather on the http://programmers.stackexchange.com page. But in any case...

My personal approach when I use a framework is to follow the style of the framework itself, and never change the coding style. To me this is important especially if I work with other developers.

Let say you want to bring someone new to the team. You can't require any more ExpressJS experience since you change the way the code is structured. Meaning you'll have to sit down with the new person and explain the different coding style.

Another thing is that turning everything in to a class is an overkill. It is an extra layer of unnecessary complexity, that you and other will have to wrap your heads around it. In addition you won't be using the benefits of the class in this case.

If it was me, I would keep the coding style as ExpressJS intended it to be, and as simple as possible :). Comments? Each route with a nice explanation like this for example:

/**
 * Nice description
 *
 * @param {string}   var-name   description
 * @param {int} var-name   description
 */
David Gatti
  • 3,576
  • 3
  • 33
  • 64