nazreen
nazreen

Reputation: 2078

Hapi v16.x.x: compose multiple route plugins into one

I currently register my routes using plugins like so:

server.js:

const movieRoutes = require('./movies/routes');
server.register([ userRoutes, movieRoutes ], err => {
...
    server.start( err => {
    ...
    });
});

movies/routes.js:

exports.register = (server,options,next) => {
   server.route(...); // first route
   server.route(...); // second route
}

Essentially I am defining all the route handlers in the above movies/route.js

What I'd like to do is to be able to split this into separate files then somehow require them back into movies/routes.js. Is there a way to do that?

In pseudocode:

movies/routes.js

exports.register = (server,options,next) => {
   // require first route
   // require second route
}

The reason I want to do this is because the routes.js is getting pretty long and I'd like to separate them into separate files.

Upvotes: 2

Views: 324

Answers (1)

Ernest Jones
Ernest Jones

Reputation: 584

You can export your functions in a file :

const fooBar = function() {}

exports.fooBar = fooBar;

Then require your handler functions in the file where you declare your routes (in pseudocode).

const fooBar = require('fooBar');
exports.register = (server,options,next) => {
  server.route({
    method: 'GET',
    path: '/path',
    handler: fooBar
  });

  next();
}

In the other hand, what I do is that I require a lot of small file containing routes in small batch… I think, it's cleaner

Upvotes: 1

Related Questions