Reputation: 3816
I've used express and there you can pass multiple methods to be passed for a route like the following:
app.get('/users/,[
validator.validate,
controller.get
]);
Each of the function then passes control to the next function in array using the next() callback. Is there something equivalent that can be done in hapijs handlers? I would want my function to be both reusable and independent like we have for express route handlers.
Thanks.
Upvotes: 3
Views: 1943
Reputation: 13567
hapi has Route Prerequisites which let you run a set of handler-like functions before the actual handler itself. These both are reusable and independent provide you define them outside of the config itself.
The value generated in each pre get's set on the request.pre
object for use in your handler. Here's an example:
var step1 = function (request, reply) {
reply('The quick brown fox ');
};
var step2 = function (request, reply) {
reply('jumped over the lazy dog.');
};
server.route({
config: {
pre: [
step1,
step2
]
},
method: 'GET',
path: '/',
handler: function (request, reply) {
var response = request.pre.step1 + request.pre.step2;
reply(response);
}
});
By default, each pre will be run in series, similar to the async.series/waterfall
function from the async package. If you want a set of pres to run in parallel to each other, just place them in an array and you'll get something like async.parallel
:
server.route({
...
config: {
pre: [
[ step1, step2 ], // these run together
step3 // and then this one
]
},
...
});
Upvotes: 6