问题
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);
}
}
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);
but in this case it returns 500 statusCode every time (but with corresponding data)
回答1:
I have been struggling with the same issue for a couple of time. Here is my hack (with explanation) to solve this.
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);
};
回答2:
Seems like only copy-paste solution existed. So I copy all code from files in node_modules/sails/lib/hooks/blueprints/actions to the actions of every controller and then change it.
来源:https://stackoverflow.com/questions/39468039/sails-blueprints-lifecycle