hapi request object

In hapi, the goal is never to monkey-patch or modify any of the normal Node objects or methods, but only to provide an extra layer around them to access the important parts.

Note

Monkey patching is the method of overriding or extending the behavior of a method. For example, let's create an add function that returns the sum of two numbers:

let add = function (a, b) {
  return a + b;
}

We now want to log in to the console every time this is called, without altering the existing behavior. We would modify it by doing the following:

let oldAdd = add;
add = function (a, b) {
  console.log('add was called…');
  return oldAdd(a, b);
}

Now every time add is called, it will print add was called…, and return the sum just as before. This can be useful in modifying core language methods, but is not a recommended pattern, as it can cause very hard-to-debug side effects. I generally limit doing this to writing tests or debugging code.

This is the case with the hapi request object. The hapi request object I refer to here is the request parameter in the route handler's request, the reply signature. It contains all the information for an incoming request. As the request passes through the hapi life cycle, extra information will be added—we saw an example of this with route prerequisites earlier, and other information such as parsed cookies, authentication credentials, and the parsed payload—but the original request object is not modified and is accessible from request.raw.req. Along with the request data, some useful properties and functions are also available from the request object:

  • request.server: This is the full server object accessible from within the route handler.
  • request.generateResponse: This returns a response to be passed into the handler.
  • request.tail: This adds a request tail task to be completed before the request life cycle, but after sending the response to the client. This is where you can do something like a database update, but shouldn't delay the response to the client, like adding audits after a request.

You can see the full request object description on hapijs.com at http://hapijs.com/api#request-object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.213.212