Reputation: 2704
Here's my default use case: I'm thinking about serving some of my REST resources over a socket.io layer instead of over http (since I end up needing to serve a lot of small api requests to render a typical page, and they're all over https, which has extra handshaking issues).
I'm still not sure this is a good idea in general (and have been looking at http2.0 as well). In the short term, I don't want to migrate off of hapijs or rewrite a ton of modular code, but I do want to try out making this work on some test servers to see how well it performs.
So I wrote a super-basic socket.io event handler that just takes requests off of the websocket event emitter and repackages them into hapi via a server.inject
call:
module.exports = {
addSocket: function(sock) {
sock.on('rest:get:request', function(sock) {
return function(url) {
console.log(url);
hapi.inject({url: url, credentials: {user: sock.user}}, function(res) {
sock.emit('rest:get:response', url, res.payload);
});
};
})(sock);
}
};
So, all it really does is make sure the authentication object is set up (I have previously authenticated the user on the socket) and then inject a GET request to the server.
Usually, it seems like server.inject
is used for testing, but this seems like a perfectly cromulent plan, unless (of course), it's super-slow or a bad idea for reasons I haven't foreseen. Hence: my question.
Upvotes: 2
Views: 315
Reputation: 7550
Server.inject
is a great way of encapsulating sub requests however it can become more complicated than necessary though. A lighter approach would be to use shared handler functions and run them as pre-handlers.
What's nice about the pre handlers is that you can run them in parellel if needed.
One use case where I have used server.inject
(other than in tests) is for a health check route. I'd have a route /health-check/db
and /health-check/queue
. I'd then have a /health-check
route which encapsulated all of them. But again, this could have been completed with shared route handlers.
I had a lengthy discussion on the gitter channel the other day about this and my understanding is that it is neither good nor bad.
I guess a really good use case would be if you have multiple teams building plugins which expose routes and you want to use one of those routes in your plugin. You don't care about the implementation; you can just call the route.
Anothe reason for using server.inject
is that it includes the validation steps provided by the route so you only need to have your resource defined in one place.
Upvotes: 2