Optional rout patterns in hapi

1k views Asked by At

http://hapijs.com/tutorials/routing

I don't see examples here for optional tokens.

While I see examples such as: "/home/token/{value?}" I do not see a way to do: "/home/optionalToken/{optionalValue?}/optionalOtherToken/{optionalOtherValue?}"

Is there a way to go about declaring optional parts of the path in more complicated patterns?

Specifically, I would like to be able to declare: "/{contentType}/page/{pageNumber?}/limit/{limitNumber?}" where page, pageNumber, limit, limitNumber are all optional parts of the path.

1

There are 1 answers

0
Simon Bartlett On

The hapi documentation has this snippet of text, which indicates that it is not possible:

An optional '?' suffix following the parameter name indicates an optional parameter (only allowed if the parameter is at the ends of the path or only covers part of the segment as in '/a{param?}/b').

However, you might be able to achieve the same end result by registering the same route multiple times with differing paths. Example:

var routeOptions = {
    method: "GET",
    handler: function(request, reply) {
        if (request.params.limitNumber) {
            ...
        }

        if (request.params.pageNumber) {
            ...
        }

        reply(...);
    }
};

var routes = [
    Hoek.applyToDefaults(routeOptions, {
        path: "/{contentType}"
    }),
    Hoek.applyToDefaults(routeOptions, {
        path: "/{contentType}/page/{pageNumber?}"
    }),
    Hoek.applyToDefaults(routeOptions, {
        path: "/{contentType}/page/{pageNumber}/limit/{limitNumber?}"
    })
];

server.route(routes);