【问题标题】:Sails blueprints lifecycle帆蓝图生命周期
【发布时间】:2016-09-13 10:40:36
【问题描述】:

我需要在find 蓝图的结果中添加一些额外的数据。我找到了这个解决方案:

module.exports = {
  find: function(req, res) {
    return sails.hooks.blueprints.middleware.find(req, res);
  }
}

但我在这里找不到任何更改响应或将回调添加到蓝图中的方法。我什至尝试更改蓝图并在其中添加 cb:

module.exports = function findRecords (req, res, cb) { 
  ...
  if (typeof cb === 'function') res.ok(cb(result));
  else res.ok(result);

但在这种情况下,它每次返回 500 个状态码(但带有相应的数据)

【问题讨论】:

  • 你想达到什么目的?您想向响应或标题添加数据吗?为什么要添加回调?
  • @zabware 我想将统计信息(关联表的计数)添加到蓝图的结果中。我在几个控制器中都需要这个,所以从 find 蓝图中复制/粘贴代码并不是很好。
  • 从关联表中填充信息很容易。第一:验证表是否真正关联(例如:models/Article.js: module.exports.attributes { ..., user = {model: 'User'}}) 第二:确保 sails.config.blueprints.populate 设置为 true . sailsjs.com/documentation/reference/blueprint-api/…

标签: node.js sails.js waterline


【解决方案1】:

我已经为同一个问题苦苦挣扎了好几次。这是我解决这个问题的技巧(附解释)。

如果发生错误,内置蓝图将始终调用res.okres.notFoundres.serverError。通过更改此方法调用,可以修改输出。

/** 
 * Lets expose our own variant of `find` in one of my controllers
 * (Code below has been inserted into each controller where this behaviour is needed..)
 */
module.exports.find = function (req, res) {

    const override = {};
    override.serverError = res.serverError;
    override.notFound = res.notFound;
    override.ok = function (data) {

        console.log('overriding default sails.ok() response.');
        console.log('Here is our data', data);

        if (Array.isArray(data)) {
            // Normally an array is fetched from the blueprint routes
            async.map(data, function(record, cb){

                // do whatever you would like to each record
                record.foo = 'bar';
                return cb(null, record);

            }, function(err, result){
                if (err) return res.error(err);
                return res.ok(result);
            });
        }
        else if (data){
            // blueprint `find/:id` will only return one record (not an array)
            data.foo = 'bar';
            return res.ok(data);
        }
        else {
            // Oh no - no results!
            return res.notFound();
        }
    };

    return sails.hooks.blueprints.middleware.find(req, override);
};

【讨论】:

  • 谢谢。我可以直接在 res 中覆盖 ok 方法吗? res.ok = function (data) {...}; return sails.hooks.blueprints.middleware.find(req, res);
  • 是的@Crusader,这听起来是个好主意!这样,res-object 上的任何其他依赖项仍然有效。 (但我还没有真正测试过你的提议。)
  • 你把这个文件放在哪里?
  • 直接进入控制器@pondermatic(所有其他出口一起)。
【解决方案2】:

似乎只有复制粘贴解决方案存在。因此,我将 node_modules/sails/lib/hooks/blueprints/actions 中文件的所有代码复制到每个控制器的操作中,然后进行更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2012-07-22
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    相关资源
    最近更新 更多