2

Im using Hapi 12.1.

Trying to figure out how to call certain extension points only on certain routes.

For example for : '/hello' I want to call three different extension points that work on the 'onRequest' step.

For: '/goodbye' I want to call a different extension point that works also on the 'onRequest' but is a different operation and a 'onPreAuth' step.

For: '/health' Dont call any extension points, and just drop into the handler straight away..

I have tried various ways to create a plugin, define the routes, and extension points. But it seems the the extension points are global, and dont only operation on the plugin's scoped routes.

What am I missing?

1 Answer 1

3

You have access to the path on your extension points, using request.route.path. With that, you can define what you want to run, depending on the path. Example:

server.ext('onPreAuth', function (request, reply) {

    switch(request.route.path) {
        case '/test1':
        case '/test2':
            // Do something

            break;
        case '/test3':
            // Do something else

            break;
    }

    reply.continue();
});

Alternatively, you can also make it dependent on the route configuration:

server.ext('onPreAuth', function (request, reply) {

    if(request.route.settings.plugins.runPreAuth) {
        // Do something

    }

    reply.continue();
});

Then, you just define in your route the configurations:

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

        reply({result: 'ok'});
    },
    config: {
        plugins: {
            runPreAuth: true
        }
    }
});
3
  • I dont think the second method works anymore. "plugins" is not allowed. You can, however, use tags: tags: ['something'] in the route definition and check it with request.route.settings.tags Commented Apr 1, 2016 at 23:10
  • @Yashua That is false... in Route options documentation, you see: plugins - plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration.. I am using it with the latest version of hapijs.
    – F. Gouveia
    Commented Apr 22, 2016 at 9:56
  • [email protected] to be more precise.
    – F. Gouveia
    Commented Apr 22, 2016 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.