Alinex
Alinex

Reputation: 979

Multiple connections on a hapi server

I want to add plugins to a hapi server which has multiple connections like listening on different ips.

Is it possible to add a plugin to all servers configured?

Or how to loop over all servers to add the plugin to all of them?

Upvotes: 4

Views: 3201

Answers (2)

Marcus Poehls
Marcus Poehls

Reputation: 461

You can create multiple connections in hapi to have multiple, internal servers available. The great thing about those separated servers: you can register plugins and routes individually only for the one that requires the functionality.

Find more details in this tutorial on how to separate frontend and backend within a single hapi project.

Hope that helps!

Upvotes: 1

Matt Harrison
Matt Harrison

Reputation: 13567

By default plugins will add routes for all connections when calling server.route().

To limit which connections the plugin adds routes to, you can use labels when creating connections and then specify those labels when registering plugins. Here's an example:

var Hapi = require('hapi');

var server = new Hapi.Server();

server.connection({ port: 8080, labels: 'a' });
server.connection({ port: 8081, labels: 'b' });
server.connection({ port: 8082, labels: 'c' });

var plugin1 = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/plugin1',
        handler: function (request, reply) {

            reply('Hi from plugin 1');
        }
    });

    next();
};
plugin1.attributes = { name: 'plugin1' };

var plugin2 = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/plugin2',
        handler: function (request, reply) {

            reply('Hi from plugin 2');
        }
    });

    next();
};
plugin2.attributes = { name: 'plugin2' };

server.register(plugin1, function (err) {

    if (err) {
        throw err;
    }

    server.register(plugin2, { select : ['a'] }, function (err) {

        if (err) {
            throw err;
        }

        server.start(function () {

            console.log('Server started');
        })
    });
});

GET /plugin1 route from plugin1 responds on :

http://localhost:8080/plugin1
http://localhost:8081/plugin1
http://localhost:8081/plugin2

where as GET /plugin2 route from plugin2 only responds on:

http://localhost:8080/plugin2

Upvotes: 4

Related Questions