Exercise 11: Validating a Request

In this exercise, we are going to see the concept of request validation in action. We will write a validation for one of the routes as an example, but the same could be applied across the other routes:

  1. For example, if we go back to the POST route from Exercise 1: Building a Basic Hapi.js Server, we can post an empty payload and still get status code 200! Clearly, we need a way of validating this.
  2. Let's start by installing Joi:
npm install joi --save

Use the exercise-c2 folder for your reference at Code/Lesson-2.
  1. In the routes/todo.js file, we need to require Joi and then modify our post route by adding a config.validate key to the route object:
{
method: 'POST',
path: '/todo',
handler: (request, reply) =>
{
const todo = request.payload;
todoList.push(todo);
return reply({ message: 'created' });
},
...
},

Use the todo.js file for your reference at Code/Lesson-2/exercise-c1/routes.
  1. When we try to submit an empty payload, we now get error 400:
  1. That is, until we provide a title for the todo, since a title is required:
Joi is a full-fledged validation library with many options for how to use it. In this exercise, we just touched on a basic example.

You validate any part of the request by coming up with the respective key/value pair within the validate key and its respective type:

payload (for request payloads, as in the preceding exercise), params (for request params), and query (for query params).

For example, for the request, GET: /todo/:id, if we want to validate that the ID is an integer, we will add this config object:
config: {
  validate:
    {

    params:
     {

      id: Joi.number()
    }
  }
}

More details on Joi can be found here: https://github.com/hapijs/joi.

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

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