I'm not completely happy with my decision, but I managed to tear out some helper functions from the kernel that bind my answer to the route after loading all the other hooks.
In particular, I copied and modified loadResponses and bindToSails from moduleloader :
let buildDictionary = require('sails-build-dictionary'); let path = require('path'); let _ = require('lodash'); function bindToSails(sails, cb) { return function (err, modules) { if (err) { return cb(err); } _.each(modules, function (module) {
Then, from the definition of my hook, I will put:
loadModules: function (cb) { let hook = this; moduleUtils.loadResponses(sails, function (err, responseDefs) { if (err) return cb(err); // Register responses as middleware hook.middleware.responses = responseDefs; return cb(); }); }, /** * Shadow route bindings * @type {Object} */ routes: { before: { /** * Add custom response methods to `res`. * * @param {Request} req * @param {Response} res * @param {Function} next [description] * @api private */ 'all /*': function addResponseMethods(req, res, next) { // Attach custom responses to `res` object // Provide access to `req` and `res` in each of their `this` contexts. _.each(sails.middleware.jsonapi.responses, function eachMethod(responseFn, name) { sails.log.silly('Binding response ' + name + ' to ' + responseFn); res[name] = _.bind(responseFn, { req: req, res: res, }); }); // Proceed! next(); } } }
Where jsonapi is the name of my hook. You can see everything in action at: https://github.com/IanVS/sails-hook-jsonapi/
source share