All of the Hapi examples (and similar in Express) shows routes are defined in the starting file:
var Hapi = require(\'hapi\');
var server = new Hapi.Server();
s
Interesting to see so many different solutions, here is another one.
For my latest project I settled on globbing for files with a particular name pattern and then requiring them into the server one by one.
server
object// Construct and setup the server object.
// ...
// Require routes.
Glob.sync('**/*route*.js', { cwd: __dirname }).forEach(function (ith) {
const route = require('./' + ith);
if (route.hasOwnProperty('method') && route.hasOwnProperty('path')) {
console.log('Adding route:', route.method, route.path);
server.route(route);
}
});
// Start the server.
// ...
The glob pattern **/*route*.js
will find all files within and below the specified current working directory with a name that contains the word route and ends with the suffix .js.
With the help of globbing we have a loose coupling between the server
object and its routes. Just add new route files and they will be included the next time you restart your server.
I like to structure the route files according to their path and naming them with their HTTP-method, like so:
server.js
routes/
users/
get-route.js
patch-route.js
put-route.js
articles/
get-route.js
patch-route.js
put-route.js
routes/users/get-route.js
module.exports = {
method: 'GET',
path: '/users',
config: {
description: 'Fetch users',
// ...
},
handler: function (request, reply) {
// ...
}
};
Globbing and iterating over files is not a particularly fast process, hence a caching layer may be worth investigating in production builds depending on your circumstances.