Inherit attributes and methods of Sails.js Models

Yeah, now I am working on an interesting Node.js project where I am using Neo4j as Graph database with Sails framework. Neo4j is very new in the market, thus there is very little good DB libraries and adapters available for Sails framework. So, I decide to write some custom model methods (using an active record pattern) in the model. The methods are required throughout all the model classes. So, I had to come with a Base Model class concept which will be extended by all other model classes. It’s a Sails framework, you have to do it differently in order to inherit as well as extends from the base class.
sails
One easy way to do this just include the methods in all the model classes like a dumb. Or, you can add all the methods globally using config/models.js like as below:

// config/models.js
module.exports.models = {
 
  sayHello: function() {
    console.log('Hello!');
  }
};

Basically, this sayHello method will be available in all of your model classes. But, I wanted to do it in a bit cleaner way. I extended it by merge() method of lodash library. Here is my code.

I put my base class in models directory

//api/models/BaseModel.js
module.exports = {
   sayHello: function() {
    console.log('Hello!');
  }
};

And, then the User class looks like below…

//api/models/User.js
var baseModel  = require('./BaseModel'),
    _          = require('lodash');
 
module.exports = _.merge({}, baseModel, {
 
//User model implmentation
...................
}

Done, sayHello method is now available in the User model. One thing is to mention that the first parameter of merge method should be {} (empty) object so that it can’t modify the baseModel. If you put the baseModel as the first parameter like _.merge(BaseModel, {…} then _.merge will modify it.

Btw, don’t forget to include lodash npm package in your project. Just type following line in your project root…

npm install lodash --save

You can also inherit attributes the above way…..

 

Eftakhairul Islam

Hi, I'm Eftakhairul Islam, a passionate Software Engineer, Hacker and Open Source Enthusiast. I enjoy writing about technical things, work in a couple of startup as a technical advisor and in my spare time, I contribute a lot of open source projects.

 

One thought on “Inherit attributes and methods of Sails.js Models

  1. This is awesome! you saved our day, we were trying to apply the solution since a long but this helped us a lot to achieve attribute to inherit in a very simple and effective manner,

    Thanks for writing this amazing post for the universe!

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Read previous post:
Write a View Helper in Laravel 5 with best practices

In my last blog post I talked about deploying Laravel 5 application in a shared hosting. Still I am working...

Close