Thursday, 27 April 2017

Best practice to create basics models in NodeJS

I'm working on a NodeJS API project. I have a lot of models (users, projects, team, ...) and for each of this model I have:

  • Models methods (getters and setters)
  • DB requests (I use Couchdb)
  • Schema validation

My first question is:

Should I create multiple modules for DB request and Class methods (in order to separate domain layer from persistance layer)?

My second question is: "How should I manage the creation of a model?"
Multiple cases:

case 1 (init constructor with Id):

var user = new User({id: 1}); 
user.fetch(function(err, user) {
   user.get('name'); // George
});

case 2 (No constructor method):

user.fetchById({id: 1}, function(err, user) { 
   user.get('name'); // George
}

case3 (Differents modules DB and domain layer):

userDB.fetchById({id: 1}, function(err, data) { 
   var user = new User(data);
   user.get('name'); // George
}

Or maybe there is other best practice? Note: I often see people making modules that represents models and that only expose DB requests.

Best regards.



via Simon Bruneaud

No comments:

Post a Comment