concept schema in category hapi

This is an excerpt from Manning's book hapi.js in Action.
Working with Joi involves a process of four steps, shown in figure 6.2. The first step is to create a schema. A schema is an object that describes your expectations and is what you’ll be checking your real data against. Think of a schema as a description of your ideal object.
There’s a common sorting game given to toddlers, where they need to place different shaped blocks into different shaped holes. This game is a good analogy to using Joi. With Joi, the schema is like the hole, and the object you want to test is like the block. Any given object is either going to fit the schema or not.
Once you have a schema, you will use Joi to test the schema against some objects. If there was a validation error, Joi will tell you precisely what went wrong. You can then use that feedback to make a decision and respond to the user appropriately.
In the previous subsection, you saw that we could specify a JavaScript string in a schema using Joi.string(). It won’t come as a huge surprise to you that the equivalent for an object is Joi.object(). Like Joi.string(), Joi.object has methods you can chain onto it to further expand the schema. One of those methods is .keys(), which allows you to add sub-schemas for each of the object’s properties. Here’s an example of creating a schema for an object with keys:
![]()
Creating schemas for objects with keys is so common that Joi also offers a convenient shorthand for the preceding. You can replace Joi.object().keys({...}) with only {...}:
Listing 6.3. Script to test the report against the schema
const Joi = require('joi'); const report = { ... }; const schema = { ... }; Joi.assert(report, schema);There should be no output before the script finishes. That indicates that the value tested was valid. In the next listing let’s try to modify the original report so it’s no longer valid according to the schema.