user3156478
user3156478

Reputation: 33

How can I write sails function on to use in Controller?

I have a question on sails js:

  1. How can I write sails function on model To use in Controler? like:
    • beforeValidation / fn(values, cb)
    • beforeCreate / fn(values, cb)
    • afterCreate / fn(newlyInsertedRecord, cb)

Upvotes: 1

Views: 2493

Answers (1)

Chad
Chad

Reputation: 2289

If you are actually trying to use one of the lifecycle callbacks, the syntax would look something like this:

var uuid = require('uuid');
// api/models/MyUsers.js
module.exports = {
  attributes: {
    id: {
      type: 'string',
      primaryKey: true
    }
  },

  beforeCreate: function(values, callback) {
    // 'this' keyword points to the 'MyUsers' collection
    // you can modify values that are saved to the database here
    values.id = uuid.v4();
    callback();
  }
}

Otherwise, there are two types of methods you can create on a model:

  • instance methods
  • collection methods

Methods placed inside the attributes object will be "instance methods" (available on an instance of the model). i.e.:

// api/models/MyUsers.js
module.exports = {
  attributes: {
    id: {
      type: 'string',
      primaryKey: true
    },
    myInstanceMethod: function (callback) {
      // 'this' keyword points to the instance of the model
      callback();
    }
  }
}

this would be used as such:

MyUsers.findOneById(someId).exec(function (err, myUser) {
  if (err) {
    // handle error
    return;
  }

  myUser.myInstanceMethod(function (err, result) {
    if (err) {
      // handle error
      return;
    }

    // do something with `result`
  });
}

Methods placed outside the attributes object but inside the model definition are "collection methods", i.e.:

// api/models/MyUsers.js
module.exports = {
  attributes: {
    id: {
      type: 'string',
      primaryKey: true
    }
  },

  myCollectionMethod: function (callback) {
    // 'this' keyword points to the 'MyUsers' collection
    callback();
  }
}

the collection method would be used like this:

MyUsers.myCollectionMethod(function (err, result) {
  if (err) {
    // handle error
    return;
  }

  // do something with `result`
});

P.S. the comments about what the 'this' keyword will be are assuming that you use the methods in a normal way, i.e. calling them in the way that I described in my examples. If you call them in a different way (i.e. saving a reference to the method and calling the method via the reference), those comments may not be accurate.

Upvotes: 8

Related Questions