giodamelio giodamelio - 5 months ago 59
Node.js Question

Hapi.js Subdomain Routing to Plugins

I am looking for a way to route different subdomains to different plugins. I looked through the API docs, and didn't find anything helpful.

Answer

I ended up making a simple class to create plugins that only work on certain subdomains. Here it is.

var Plugin = function(attributes, routes) {
    // Add our routes to the server
    this.register = function(plugin, options, next) {
        // Loop through the selected servers and add the routes
        plugin.servers.forEach(function(server) {
            // Loop through the routes and add the vhost option
            routes.map(function(route) {
                route.vhost = attributes.vhosts.map(function(vhost) {
                     return vhost + "." + server.info.host;
                });
            });

            // Add the routes
            server.route(routes);
        });
        next();
    };

    // Add our attributes
    this.register.attributes = attributes;
};

Then you can make a new plugin and specify the subdomains easily. Example:

var plugin = new Plugin([
    // Your route or routes here
], {
    vhosts: ["array", "of", "subdomains"]
});
Comments