Custom Model Validator SailsJS

125 views Asked by At

When using a custom model validator that checks for a record within a model. The return within the spread doesn't seem to end the control flow.

//Post.js Model  

  /**
   *  Custom Validator
   **/
  types: {
    isUserValid: function(user_id) {
      var Promise = require('bluebird');

      Promise.all([
        User.findOne({id: user_id})
      ])
        .spread(function(user) {
          console.log(user);
          if (user === null || user === undefined) {
            console.log('failed');
            return false;
          }else{
            console.log('passed');
            return true;
          }
        });
    }
  },

My response is a standard validation failed response.

{
  "error": "E_VALIDATION",
  "status": 400,
  "summary": "1 attribute is invalid",
  "model": "Post",
  "invalidAttributes": {
    "owner": [
      {
        "rule": "isUserValid",
        "message": "\"isUserValid\" validation rule failed for input: 1"
      }
    ]
  }
}
1

There are 1 answers

0
Evilsanta On

looks like you want the "return true and return false" to be the return of the isUserValid function. but in fact it is not how the javascript scope work. the return statement return true inside your spread function only means the promise is resolved with "true". it is not returned as the function. the function isUserValid still returns nothing. if this function can be an async promise. you should at least return the promise.

return Promise.all([....]).spread.....

infact it canbe simplified

return User.findOne(user_id).then(function(u){....})

However, if this function does not support promise, meaning it is synchronous, and expects a true/false to be returned, instead of a promise object. You have to make this process a synchronous. One way to convert a promise into synchronous is using generator function. See here