Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sails.js

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?

like image 533
harisreeram Avatar asked Jun 23 '15 21:06

harisreeram


2 Answers

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

    });
} 
like image 75
jaumard Avatar answered Nov 01 '22 08:11

jaumard


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
        }
      ));
    }
like image 23
Theophilus Omoregbee Avatar answered Nov 01 '22 08:11

Theophilus Omoregbee