sails.jswaterlinecalculated-columnscalculated-fieldcustom-attribute

Sails js custom/calculated attributes is not working, using code from sails docs


I have this model that is taken from this sails documentation page

module.exports = {

    attributes: {
    // Primitive attributes
    firstName: {
      type: 'string',
      defaultsTo: ''
    },
    lastName: {
      type: 'string',
      defaultsTo: ''
    },

    // Attribute methods
    getFullName: function (){
      return this.firstName + ' ' + this.lastName;
    }
  }
};

What I expect when I call my auto generated restful api (using blueprint)

localhost:port/resourceName

is

{"firstName":"john", "lastName":"Doe", "getFullName": "john Doe"}

instead what I am getting is this

{"firstName":"john", "lastName":"Doe"}

any ideas?

I already checked other posts such as this one github.

sails version: 0.11.4

Thanks a lot :)


Solution

  • If you want the custom attribute to be serialised you can override the default toJSON instance method:

    toJSON: function() {
      var obj = this.toObject();
      obj.fullName = this.getFullName();
      return obj;
    }