Call a hapi route from another route

2019-06-19 07:03发布

问题:

I am pretty new to HapiJS. I am building a service where I have two routes /route1 and /route2 both are using the plugin architecture. I have registered both as plugins on my manifest file.

I want to call /route1 from /route2 so /route2 depends on the payload reply from /route1. I've been looking at putting the logic of /route2 on /route1 on the pre-handler but I want to keep them separately.

Don't know how to call a registered plugin from another the thing is that both plugins (routes) are making networks requests. Thanks for reading.

Thanks.

回答1:

As you specify that you don't want to use a shared handler/route prerequisite (which would be my first choice), you could make an actual request using a http client (Wreck, request, http or the like).

Another, more efficient way that doesn't involve actually making a network request is to use hapi's built-in server.inject() method provided by Shot. This will inject a request into your server and get the response, which you can use. Here's an example:

var Hapi = require('hapi');

var server = new Hapi.Server();
server.connection({ port: 4000 });

var plugin1 = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/route1',
        handler: function (request, reply) {

            reply('Hello');
        }
    });

    next();
};

plugin1.attributes = { name: 'plugin1' };

var plugin2 = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/route2',
        handler: function (request, reply) {

            server.inject('/route1', function (res) {

                reply(res.payload + ' World!');
            });
        }
    });

    next();
};

plugin2.attributes = { name: 'plugin2' };

server.register([plugin1, plugin2], function (err) {

    if (err) throw err;
    server.start(function (err) {
        if (err) throw err;
        console.log('Started');
    });
});

Note that the fact the routes are in plugins here is irrelevant. I've merely included it so it's close to your situation.

Shot and server.inject() are primarily used for testing but there are legitimate runtime uses like this too.

If you make a request to /route2, this will invoke /route1 handler and get the payload:

$ curl localhost:4000/route2
Hello World!