Storm
Storm

Reputation: 4445

Hapijs route registration pattern

As the "Inert" plugin now has to be loaded separately. I want to register the routes of my application. I have 2 choices

1) Export a function that takes "server" as an argument and write code as

module.exports = function(server) {
    server.register('inert', function(err) {});

    server.routes([....]);
}

And simply call it from server.js as require('./routes.js')(serverObj)

2) Export the routing mechanism as a hapi plugin

exports.register = function(server, opts, next) {
    server.register('inert', function(err) {});

    server.routes([....]);

    next();
}

and call it from server.js as server.register(require('./routes.js'), function(err) {});

Which is a better / more standardized approach ? OR is there a 3rd way I don't know about.

Side Q: Also, should I register the 'inert' plugin before calling the route function / plugin in the server.js file ?

Upvotes: 0

Views: 820

Answers (1)

Matt Harrison
Matt Harrison

Reputation: 13567

server.route() can be passed an array of routes so you could simply export routes as an array:

routes.js

module.exports = [
    {
        method: 'GET',
        path: '/',
        handler: function (request, reply) {

            ...
        }
    },
    ...
];

And then require that file when you're doing the main app setup:

index.js

server.register(require('inert'), function (err) {

    if (err) {
        throw err;
    }

    server.route(require('./routes'));
    server.start(...)
});

Side Q: Also, should I register the 'inert' plugin before calling the route function / plugin in the server.js file ?

Yes, if you're using the file handler or the directory handler, you need to make sure inert is loaded first, otherwise you'll get an error when registering the routes.

If you choose to register routes in a plugin that depends on these handlers, you can use server.dependency() to express this dependency and delay registering the routes until inert is loaded. This means you don't have to care about which order you list your plugins in server.register(). Useful if you're working with lots of plugins or on a big application/team.

Upvotes: 1

Related Questions