harisreeram
harisreeram

Reputation: 89

How to cancel the creation of a record in Sails in beforeCreate

I know that Sails automatically creates a record when you pass it the appropriate fields through the create URL. When a new record created, I need to see if the record exists or not. If it doesn't exist, I create it. If it does exist, I should not create it. I have successfully checked to see if the record exists or not, but I'm confused on what to do if the record does exist. How do I tell Sails to not create the record?

beforeCreate: function(values, cb) {

  User.findOne({ where: { name: values.name}}).exec(function(err, found) {
    if(found == undefined) console.log("NOT FOUND"); //create the record
    else console.log("FOUND"); //don't create the record
  });

  cb();

}

When Sails hits the cb() it automatically creates the record. How do I make it so that I decide whether or not to create the record?

Upvotes: 5

Views: 556

Answers (2)

Theophilus Omoregbee
Theophilus Omoregbee

Reputation: 2503

The best way to handle this for the future devs, is to stick with the validation mechanism by waterline WLValidationError

beforeCreate: function (values, cb){

    //this is going to throw error 
    var WLValidationError = require('../../node_modules/sails/node_modules/waterline/lib/waterline/error/WLValidationError.js');

    cb(new WLValidationError({
          invalidAttributes: {name:[{message:'Name already existing'}]},
          status: 409
         // message: left for default validation message
        }
      ));
    }

Upvotes: 1

jaumard
jaumard

Reputation: 8292

Instead of beforeCreate function use the beforeValidate function that can stop the creation (http://sailsjs.org/#!/documentation/concepts/ORM/Lifecyclecallbacks.html).

beforeValidation: function(values, next){
 User.findOne({ where: { name: values.name}}).exec(function(err, found) {
    if(found == undefined){
        console.log("NOT FOUND"); //create the record
        next();
    }
    else{ 
       console.log("FOUND"); //don't create the record
       next("Error, already exist");  
    }

    });
} 

Upvotes: 5

Related Questions