自定义模型验证器SailsJS

时间:2015-06-14 12:17:19

标签: node.js sails.js sails.io.js

使用自定义模型验证程序检查模型中的记录时。价差的回报似乎并没有结束控制流程。

//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;
          }
        });
    }
  },

我的回复是标准验证失败的回复。

{
  "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 个答案:

答案 0 :(得分:2)

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

相关问题