kissbudai
kissbudai

Reputation: 63

How to achieve MVC pattern in sails?

I'm wondering what is the best way to achieve the MVC pattern is sails.js.

Now I have the following structure: I have a route which redirects the request to the controller:

'POST /api/user/...': {controller: 'UserController', action: 'someFunction'},

My user model:

module.exports = {
    ...
    attributes: {...}
}

I have the controller:

someFunction: function(req, res) {
    let param = req.body.param;
    let userId = req.session.userId;
    userService.someFunction(userId, param, function (result) {
        return res.json({result});
    });
},

And in the userService I have methods for manipulating the database, for example:

someFunction: function(userId, param, callback){
    User.findOne(userId).exec(function (err, user){
                    if (err) {
                        callback(false);
                    } else {
                        // find the user's additional info
                        User.update({name: param}, { ... })
}

My real question is that is this a good pattern to follow or I'm on the wrong path.

Thanks for any kind of response.

Upvotes: 0

Views: 142

Answers (1)

Sangharsh
Sangharsh

Reputation: 3019

Note: Answer to this question can be opinion-based. Here is my opinion.

Sails project is scaffolded in MVC pattern. There are separate folders for Models (api/models), Controllers (api/controllers), and Views (views).

You're doing right thing having database methods in Services.
Anything that can be required by more than one controller action should go into services.

Other thoughts:

  • Any logic which deals with a single model should be in that Model
  • Prefer to apply constraints, foreign keys at database level as well
  • With Node.js v7.6+, you can use async/await. Sails (Waterline) methods return Bluebird promises which works well with async/await.

Upvotes: 1

Related Questions