简体   繁体   中英

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();
    }
  }
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM