liveBook · Manning

Ajv

As explained in Data-Oriented Programming: Reduce software complexity

Ajv is a JavaScript library that compiles JSON Schema definitions into functions for validating data.

Ajv is a JavaScript library that turns JSON Schema definitions into validation functions. It helps boundary data fail clearly instead of leaking malformed requests into the system. section 7.6

When a search request goes wrong

A request uses myTitle instead of title. After validation, ajv.errors contains structured details such as the missing property. Call ajv.errorsText(ajv.errors) to produce a readable message. By default, Ajv reports the first failure; construct it with {allErrors: true} to collect several failures, including invalid array items. section 7.5

Listing 7.23 Catching multiple validation failures
var searchBooksRequestSchema = {
  "type": "object",
  "properties": {
    "title": {"type": "string"},
    "fields": {
      "type": "array",
      "items": {"type": "string"}
    }
  },
  "required": ["title", "fields"]
};
 
var invalidSearchBooksRequest = {         #1
  "myTitle": "habit",
  "fields": [1, 2]
};
 
var ajv = new Ajv({allErrors: true});     #2
 
ajv.validate(searchBooksRequestSchema, 
  invalidSearchBooksRequest);
 
ajv.errorsText(ajv.errors);               #3
// → "data must have required property 'title', 
// →  data/fields/0 must be string, 
// →  data/fields/1 must be string"

A compact listing shows how allErrors changes validation from one reported problem to a readable set of failures. section 7.5

How Data-Oriented Programming: Reduce software complexity covers it

How deep it goes
Explains structured errors, readable formatting, and allErrors, while deferring advanced validation.
Examples
Uses invalid search-book requests with missing properties and incorrectly typed array items.
What it assumes
Uses JavaScript objects, JSON Schema definitions, and validator instances as its working setup.
What you can do after
Diagnose failures with ajv.errors, format them with errorsText, and configure allErrors for multiple failures.
How it connects
Connects JSON Schema, data validation, external data sources, and validation failures.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming: Reduce software complexity. The section links point to the parts of the book it draws on.