How to use `pre` in route handler - hapi.js

Anusha Nilapu picture Anusha Nilapu · Jul 15, 2015 · Viewed 9.6k times · Source

I have to call a method using pre in a route. I am using hapi-request. I tried to use pre in the route declaration, but I got an error. What am I missing?

My original route:

server.route({ 
    method: 'POST', 
    path: '/searchUser',  
    config: User.searchUser
})

Using Pre

server.route({ 
    method: 'POST', 
    path: '/searchUser',  
    pre: validateUser, 
    config: User.searchUser
})

Error

Error: Invalid route options (/searchUser) {
  "method": "POST",
  "path": "/searchUser",
  "config": {}
}
←[31m
[1] "pre" is not allowed←[0m   

Answer

Anusha Nilapu picture Anusha Nilapu · Jul 17, 2015

pre should be used inside the config object.

From the route-prerequisites documentation in Hapi:

server.route({
    method: 'GET',
    path: '/',
    config: {
        pre: [
            [
                // m1 and m2 executed in parallel
                { method: pre1, assign: 'm1' },
                { method: pre2, assign: 'm2' }
            ],
            { method: pre3, assign: 'm3' },
        ],
        handler: function (request, reply) {
            return reply(request.pre.m3 + '\n');
        }
    }
});

Updated Route:

server.route({ 
    method: 'POST', 
    path: '/searchUser', 
    config: {
        handler: User.searchUser, 
        pre: [{ method: validate /* function to be called */ }]
    }
);