gpt4 book ai didi

node.js - Sails 蓝图生命周期

转载 作者:太空宇宙 更新时间:2023-11-03 23:29:55 24 4
gpt4 key购买 nike

我需要向 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 statusCode(但带有相应的数据)

最佳答案

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

如果发生错误,蓝图中的构建将始终调用 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);
};

关于node.js - Sails 蓝图生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39468039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com