Sails 蓝图生命周期 [英] Sails blueprints lifecycle

查看:43
本文介绍了Sails 蓝图生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to add some additional data to result of find blueprint. I found this solution:

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

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

but I can`t find any way to change response here, or add callback into the blueprint. I even try to change blueprint and add the cb in it:

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

但在这种情况下,它每次都返回 500 statusCode(但带有相应的数据)

but in this case it returns 500 statusCode every time (but with corresponding data)

推荐答案

我一直在为同样的问题苦苦挣扎一段时间.这是我解决此问题的技巧(附说明).

I have been struggling with the same issue for a couple of time. Here is my hack (with explanation) to solve this.

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

The build in blueprint will always make a call to res.ok, res.notFound, or res.serverError if an error occurs. With altering of this method calls, it is possible to modify the output.

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

这篇关于Sails 蓝图生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆