【问题标题】:Derived attribute absent in JSON response in Sails.jsSails.js 中的 JSON 响应中缺少派生属性
【发布时间】:2015-09-13 10:18:16
【问题描述】:

我正在为示例应用中的用户编写 API。 api/models/User-文件如下所示:

module.exports = {
  attributes: {
    firstName: {
      type: 'string',
      required: true
    },
    lastName: {
      type: 'string',
      required: true
    },
    fullName: function () {
      return this.firstName + ' ' + this.lastName;
    }
  }
};

但是,当我find我所有的用户时,在响应中找不到派生属性:

[
  {
    "firstName": "Marlon",
    "lastName": "Brando",
    "createdAt": "2015-09-13T10:05:15.129Z",
    "updatedAt": "2015-09-13T10:05:15.129Z",
    "id": 8
  },
  {
    "firstName": "Bjoern",
    "lastName": "Gustavsson",
    "createdAt": "2015-09-13T10:05:36.221Z",
    "updatedAt": "2015-09-13T10:05:36.221Z",
    "id": 10
  },
  {
    "firstName": "Charlie",
    "lastName": "Sheen",
    "createdAt": "2015-09-13T10:06:59.999Z",
    "updatedAt": "2015-09-13T10:06:59.999Z",
    "id": 11
  }
]

是我遗漏了什么,还是根本不可能派生出这样的属性?

【问题讨论】:

    标签: json rest sails.js


    【解决方案1】:

    当您在 Model with function 中设置属性时,并不意味着它将在结果属性中执行。这意味着您可以在代码中调用此函数。例如,我正好有你的 User 模型。我可以像这样在我的代码中制作:

    // api/controllers/UserController.js
    module.exports = {
      index: function(req, res) {
        User
          .create({firstName: req.param('firstName'), lastName: req.param('lastName')})
          .then(function(user) {
            console.log(user.fullName());
            return user;
          })
          .then(res.ok)
          .catch(res.negotiate);
      }
    };
    

    如果你想让它像一个动态属性,那么你应该看看你的模型中的toJSON 方法。您可以覆盖它并实现自己的逻辑。我认为在你的情况下它看起来像这样:

    // api/models/User.js
    module.exports = {
      attributes: {
        firstName: {
          type: 'string'
        },
    
        lastName: {
          type: 'string'
        },
    
        fullName: function() {
          return [this.firstName, this.lastName].join(' ');
        },
    
        toJSON: function() {
          var obj = this.toObject();
          obj.fullName = this.fullName();
          return obj;
        }
      }
    };
    

    我没有检查此代码,但认为应该可以。你可以使用toJSON 方法来看看你得到了什么。如果代码不起作用,请在 cmets 中 Ping 我。

    【讨论】:

    • 完美的 Eugene :) 玩了 Sails 几天了,这对我来说就像是最后一块拼图。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2017-11-29
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2018-07-19
    相关资源
    最近更新 更多