Call the Hapi route from another route

I am new to HapiJS. I am creating a service where I have two routes / route 1 and / route2, both using the plugin architecture. I registered both as plugins in my manifest file.

I want to call / route 1 from / route2, so / route 2 depends on the response of the payload from / route 1. I looked at the logic of / route 2 on / route1 on the preprocessor, but I want to save them separately.

I don’t know how to call a registered plug-in from another, because both plug-ins (routes) create network requests. Thank you for reading.

Thanks.

+5
source share
1 answer

As you pointed out that you do not want to use the precondition of a common handler / route (which would be my first choice), you could make the actual request using an http client ( Wreck , request , http or the like).

Another, more efficient way that is not related to actually executing a network request is to use the built-in server.inject() hapi method provided by Shot . This will add a request to your server and get a response that you can use. Here is 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'); }); }); 

Please note that the fact that the routes are in the plugins here does not matter. I just turned it on so that it was close to your situation.

Shot and server.inject() are mainly used for testing, but there are legitimate execution features like this.

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

 $ curl localhost:4000/route2 Hello World! 
+8
source

Source: https://habr.com/ru/post/1233478/


All Articles