If you have been programming long enough then you know all too well that you can never trust external data.
The first thing you will want to do is validate this data before it becomes too ingrained into your program.
You may have already heard the saying “don't roll your own crypto”.
Though less complex, the same thing can be said about validation, as you can fall into a variety of traps that library maintainers have already considered extensively and fixed for you.
One of the libraries that does that for you is called joi. Full disclosure, I am the maintainer of that library.
But before we dive in, a little disclaimer. You can use joi as a way to ensure the shape and integrity of data.
Although you could dip a bit into semantic validation (making sure that things actually make sense), I wouldn't go as far as saying you could check all your business rules with it, so your mileage may vary.
Joi's usefulness can be separated into two distinct parts.
So let's illustrate the schema part with a made up example :
This article is only meant to cover the very basics of what joi is, its purpose and usage.
Of course, as with any tool, there is a learning curve to be able to fully express yourself with it, but hopefully not too steep of one.
Now, is it a silver bullet? Obviously not, there's no such thing.
It's a constant work in progress to both ensure that the data that comes out of joi is the data you would expect, while still being as approachable and safe as possible for developers.
Sometimes features are missing. The main one right now in my mind being the lack of asynchronous validations (you often don't need it, but still). But, joi can be extended with custom rules, and when it's not enough, hey it's open source, so if you feel motivated, come to me so we can draft a path forward!
Also, if you are interested in hapi.js check out our article on hapi.js performance
Image: bady qb