Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Getting Started with hapi.js

You're reading from  Getting Started with hapi.js

Product type Book
Published in Apr 2016
Publisher
ISBN-13 9781785888182
Pages 156 pages
Edition 1st Edition
Languages

Chapter 6. The joi of Reusable Validation

In this chapter, we're going to look at validation in Node and also at joi, the object schema validator used throughout the hapi framework and its ecosystem.

We have actually already touched on joi in Chapter 2, Adding Functionality by Routing Requests, when we saw a then unfamiliar type description on a request parameter in our route configuration example. However, joi isn't limited to validating request properties, or even to use within hapi. It is a standalone object schema validation library that can be used in any Node application. Before we delve into some joi syntax and examples, let's first explore the topic of validation first.

An introduction to validation


In pretty much any type of application, we are going to work with data, and of course, we need to ensure that this data is of a certain type or structure before we can act on it. This poses a number of problems. First, how do we easily define the way we want our data to be structured (often referred to as a schema), and second, how can we provide feedback in a consistent manner if the data provided isn't structured the way we want.

As with testing, if it's not easy to write or understand a schema, often, as developers, we won't do it, and instead, resort to very primitive attempts such as:

…
if (typeof username !== 'string') {
  // throw or return error
}
// perform action
…

First of all, please note that if you find yourself doing this, you're going to have huge problems as your application logic grows. You might have already seen examples of this—massive validation functions for performing actions with different combinations of properties.

This is hugely counterproductive...

Introduction to joi


As mentioned earlier, joi (https://github.com/hapijs/joi) is an object schema validation library used in nearly every module throughout the hapi ecosystem. If you tried adding an incorrect configuration object to a connection, a route configuration object, or when registering plugins, and found that the server threw a detailed validation error, that was joi at work. When the hapi team were going for a configuration-over-code approach for building a framework, having an excellent object schema validator to validate all the configuration objects and provide detailed errors was important. The same goes for when building an application.

Similar to testing, validation is one of those things that developers might not give the full effort to in projects, as the repercussions aren't immediately obvious. If it's not made easy, it might not be done properly. Fortunately, joi has such an easy-to-use fluent API, that using method chaining, which I'll show soon, makes it very easy...

Validating hapi routes with joi


Now that we have learned about the importance of validation and the flexibility of joi, let's look at where we can apply it in our hapi applications. Fortunately, hapi provides first class support for validation on its route configuration objects. We saw this very briefly in Chapter 2, Adding Functionality by Routing Requests, both on a route configuration object and where the validation steps take place within the request life cycle.

On a route configuration object, we can provide validation rules through a validate object. With this, we can define specific validation rules for the request headers, parameters, query, payload, and also on the response. It might not be immediately obvious why we would validate our response, but we'll look at that further on in the chapter. Let's first look at an example of a route configuration with added validation rules.

Let's take our user store application from the previous chapters, and add some validation. If you remember...

Documentation generation


When I was first investigating Node frameworks for building an API, documentation generation was a hugely important feature that I needed. I was building a public API for a proprietary system at the time. Without good documentation, this, or any API, wouldn't garner much usage as you can probably imagine.

As the initial writing of API documentation is a huge chore, one which I don't enjoy anyway, the even more time consuming task is to constantly try to update documentation to keep it in sync with the latest version of the API. For an API under constant development, this would become a huge time sink, and so drove the need for documentation generation. In most frameworks, this generally comes from requiring annotations, and/or compromising the flexibility of route configuration, which aren't great options.

Fortunately, the configuration-over-code approach of hapi lends itself quite well to being able to generate documentation, as we can generate a full routing table...

Summary


In this chapter, we've looked at the topic of validation and joi, the object schema validation library used throughout the hapi ecosystem. We looked at the importance of validating our inputs, and how to keep this work manageable by using joi.

Hopefully, this chapter has given you a good grounding in the flexibility of joi, and also in how to make your code more robust and readable so that you can use joi both within or outside of hapi applications. I recommend having a full read of joi's documentation and repo examples before moving on to the next chapter.

One of the drawbacks of joi at the moment is that it only supports server-side validation out of the box. However, as popularity grows, I expect this to change in the future, and with tools such as browserify and webpack, it is possible to use joi in the browser with some work; however, that is outside the scope of this book.

As always, all code samples seen in here as well as some extra material can be found online in the repository...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Getting Started with hapi.js
Published in: Apr 2016 Publisher: ISBN-13: 9781785888182
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}