alevkon
alevkon

Reputation: 327

Cancelling default behaviour in sails.js model Lifecycle callback

Let's say we create a sails.js model, which sometimes should be saved into DB when posted (as usual), and sometimes – should not. Can we perform this logic in a model lifecycle callback?

Basically, it gives us just two ways – proceed as usual calling next() or raise an error calling next(err). Are there any other options? Maybe it's somehow possible to get access to req/res objects from inside the callback?

module.exports = {

  attributes: {
  },

  // Lifecycle Callbacks
  beforeCreate: function(values, next) {
    //analyze values

    if (someCondition) {
      //now we realize that we don't want the model to be created
      //we need perform some other stuff and respond with some custom answer
      //how do we do that?
    } else {
      next();
    }
  }
};

Upvotes: 3

Views: 834

Answers (1)

particlebanana
particlebanana

Reputation: 2416

So that's the job of the Controller, you don't want to bring in req/res objects to the model. The check to see if a record should be created or not belongs in a controller method. By the time Model.create() is called you should already know if you want to create it or not. If you want to use the Blueprints or reduce code repetition you can use a policy (middleware) that you can attach to routes and do the check before the Model.create() is called.

Upvotes: 4

Related Questions