Sails蓝图填充不起作用于创作?

时间:2015-08-15 21:47:43

标签: sails.js

根据this,在创建与其他记录关联的新记录时,响应应包含已填充的相关记录。

POST /pony
{
  "name": "Pinkie Pie",
  "pet": 1
}

响应应该像

{
  "name": "Pinkie Pie",
  "pet": {
    "name": "Gummy",
    "id": 1
  },
  "id": 4,
  "createdAt": "2013-10-18T01:22:56.000Z",
  "updatedAt": "2013-11-26T22:54:19.951Z"
}

相反,我实际上得到了"pet": 1作为回应。

我的步骤是这样的:

  1. sails new test
  2. sails generate api pony
  3. sails generate api pet
  4. "name" : "string"添加到两个模型
  5. "pet" : { "model" : "pet" }添加到小马模型
  6. 我是否应该做任何其他事情来获取蓝图api填充pet属性以响应pony创建,或者我是否必须再做一个请求才能填充宠物?

2 个答案:

答案 0 :(得分:4)

默认情况下,blueprint操作的create未通过创建的任何新实例执行populateAll。看看它的source code

如果您要自动填充已创建的内容,则应在blueprint操作时覆盖默认create,类似于。

create: function(req, res){
  var Model = actionUtil.parseModel(req);

  // Create data object (monolithic combination of all parameters)
  // Omit the blacklisted params (like JSONP callback param, etc.)
  var data = actionUtil.parseValues(req);


  // Create new instance of model using data from params
  Model.create(data).exec(function created (err, newInstance) {

    // Differentiate between waterline-originated validation errors
    // and serious underlying issues. Respond with badRequest if a
    // validation error is encountered, w/ validation info.
    if (err) return res.negotiate(err);

    // If we have the pubsub hook, use the model class's publish method
    // to notify all subscribers about the created item
    if (req._sails.hooks.pubsub) {
      if (req.isSocket) {
        Model.subscribe(req, newInstance);
        Model.introduce(newInstance);
      }
      Model.publishCreate(newInstance, !req.options.mirror && req);
    }

    // Send JSONP-friendly response if it's supported
    // populate it first
    Model
      .findOne({id:newInstance.id})
      .populateAll()
      .exec(function(err, populatedInstance){
        if (err) return res.negotiate(err);

        res.created(populatedInstance);
      });
  });
}

答案 1 :(得分:1)

安迪的回答很明显。这是使用水线承诺的实现

<强> API /蓝图/ create.js

'use strict';

let actionUtil = require('sails/lib/hooks/blueprints/actionUtil')

/**
 * Create Record
 *
 * post /:modelIdentity
 *
 * An API call to find and return a single model instance from the data adapter
 * using the specified criteria.  If an id was specified, just the instance with
 * that unique id will be returned.
 *
 * Optional:
 * @param {String} callback - default jsonp callback param (i.e. the name of the js function returned)
 * @param {*} * - other params will be used as `values` in the create
 */
module.exports = function createRecord (req, res) {
  var Model = actionUtil.parseModel(req);

  var data = actionUtil.parseValues(req);

  Model
    .create(_.omit(data, 'id'))
    .then(newInstance => Model.findOne(newInstance.id).populateAll())
    .then(res.created)
    .catch(res.negotiate);
}