Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HapiJS global path prefix

I'm writing an API on HapiJS, and wondering how to get a global prefix. For example, all requests should be made to:

https://api.mysite.com/v0/...

So I'd like to configure v0 as a global prefix. The docs (here) don't seem to mention it -- is there a good way to do this in HapiJS?

like image 401
Tyler Avatar asked Jan 10 '15 00:01

Tyler


2 Answers

If you put your API routing logic inside a Hapi plugin, say ./api.js:

exports.register = function (server, options, next) {

    server.route({
        method: 'GET',
        path: '/hello',
        handler: function (request, reply) {
            reply('World');
        }
    });

    next();

};

exports.register.attributes = {
    name: 'api',
    version: '0.0.0'
};

You register the plugin with a server and pass an optional route prefix, which will be prepended to all your routes inside the plugin:

var Hapi = require('hapi');

var server = new Hapi.Server()
server.connection({
    port: 3000
});

server.register({
    register: require('./api.js')
}, {
    routes: {
        prefix: '/v0'
    }
},
function(err) {

    if (err) {
        throw err;
    }

    server.start(function() {
        console.log('Server running on', server.info.uri)
    })

});

You can verify this works by starting the server and visiting http://localhost:3000/v0/hello.

like image 150
Matt Harrison Avatar answered Sep 20 '22 02:09

Matt Harrison


I was able to get it working for all routes with

var server = new Hapi.Server()
...
server.realm.modifiers.route.prefix = '/v0'
server.route(...)
like image 32
Tyler Avatar answered Sep 21 '22 02:09

Tyler