Sails blueprints lifecycle

风流意气都作罢 提交于 2019-12-02 14:08:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!