Is there a way to view all routes on a Hapi server

We are working on a node.js Hapi server that retrieves the list of routes from the MongoDB database and configures the specified routes for maintenance. At the same time, there is a possibility of server failure due to duplicate route entries in the database.

I tried to look, but could not find a way to check the repeating routes in Hapi.

Is it possible to get a list of routes served by the Hapi server?

Is there a mistake I can make that is better than the standard try / catch block when trying to build routes coming from MongoDB?

The code that sets up the routes is shown below; see my comments in the code where I need to handle the error.

MySchema.find({}, function (err, stubs) { if (err) { console.log('error while loading'); return; } for (var i = 0; i < stubs.length; i++) { var bodyMessage = stubs[i].body; // This is where we can fail, if only I could make a // check for the route here server.route({ method: stubs[i].method, path: stubs[i].path, handler: function (request, reply) { reply(bodyMessage); } }); } }); 
+5
source share
3 answers

Perhaps server.table() will help you? It returns a copy of the routing table. Example from the docs page:

 var table = server.table() console.log(table); /* Output: [{ method: 'get', path: '/test/{p}/end', settings: { handler: [Function], method: 'get', plugins: {}, app: {}, validate: {}, payload: { output: 'stream' }, auth: undefined, cache: [Object] } }] */ 
+12
source

I am using Hapi version 15.1.1 and what works for me:

  // server.select if you have more than one connection const table = server.select('api').table(); let routes = []; table[0].table.forEach((route) => { // you can push here the route to routes array routes.push(route); }); 
+1
source

To change a specific route, you can view them with the key using the .match () method inside obj connections.

 var routeObj = server.connections[0].match('get', '/example', '<optional host>') routeObj.settings.handler = function(req, reply){ reply({"statusCode":404,"error":"Not Found"}) } 

If you have multiple connection loops through them, to change them. The above changes the route handler to 404, since you should not delete routes.

Routes are stored in an object indexed by the path in hapi / node_modules / call

+1
source

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


All Articles