Comprehensive schema management system for organizing, caching, and accessing schemas with support for remote references, meta-schemas, and schema validation.
Adds a schema to the validator instance with optional key for later retrieval and reference resolution.
/**
* Adds a schema to the validator instance
* @param schema - Schema to add
* @param key - Optional key for schema retrieval
* @param strict - Override strict mode for this schema
* @param meta - Whether this is a meta-schema
* @returns The Ajv instance for chaining
*/
addSchema(schema: AnySchema, key?: string): Ajv;
addSchema(schema: AnySchema, key: string, strict?: boolean, meta?: boolean): Ajv;
addSchema(schema: AnySchema[], key?: string, strict?: boolean, meta?: boolean): Ajv;Usage Examples:
import Ajv from "ajv";
const ajv = new Ajv();
// Add schema with key
ajv.addSchema({
$id: "https://example.com/user.json",
type: "object",
properties: {
name: { type: "string" },
email: { type: "string", format: "email" }
}
}, "user");
// Add multiple schemas
ajv.addSchema([
{
$id: "https://example.com/address.json",
type: "object",
properties: {
street: { type: "string" },
city: { type: "string" }
}
},
{
$id: "https://example.com/phone.json",
type: "string",
pattern: "^\\+?[1-9]\\d{1,14}$"
}
]);
// Reference schemas in other schemas
const userSchema = {
type: "object",
properties: {
user: { $ref: "https://example.com/user.json" },
address: { $ref: "https://example.com/address.json" },
phone: { $ref: "https://example.com/phone.json" }
}
};
const validate = ajv.compile(userSchema);Adds meta-schemas used for validating other schemas, enabling schema-of-schemas validation.
/**
* Adds a meta-schema for validating other schemas
* @param schema - Meta-schema definition
* @param key - Optional key for meta-schema retrieval
* @param strict - Override strict mode for this meta-schema
* @returns The Ajv instance for chaining
*/
addMetaSchema(schema: AnySchemaObject, key?: string): Ajv;
addMetaSchema(schema: AnySchemaObject, key: string, strict?: boolean): Ajv;Usage Examples:
import Ajv from "ajv";
const ajv = new Ajv();
// Custom meta-schema for API schemas
const apiMetaSchema = {
$id: "https://example.com/api-meta-schema.json",
type: "object",
properties: {
type: { type: "string" },
properties: {
type: "object",
additionalProperties: {
anyOf: [
{ $ref: "#" },
{ type: "boolean" }
]
}
},
apiVersion: {
type: "string",
enum: ["v1", "v2", "v3"]
}
},
required: ["type", "apiVersion"]
};
ajv.addMetaSchema(apiMetaSchema, "api-meta");
// Now schemas can use this meta-schema
const userSchema = {
$schema: "https://example.com/api-meta-schema.json",
type: "object",
apiVersion: "v2",
properties: {
id: { type: "integer" },
name: { type: "string" }
}
};Removes schemas from the validator cache by key, regular expression pattern, or clears all cached schemas.
/**
* Removes cached schemas
* @param schemaKeyRef - Schema key, RegExp pattern, or omit to clear all
* @returns The Ajv instance for chaining
*/
removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv;Usage Examples:
import Ajv from "ajv";
const ajv = new Ajv();
// Add some schemas
ajv.addSchema({ $id: "user", type: "object" }, "user");
ajv.addSchema({ $id: "product", type: "object" }, "product");
ajv.addSchema({ $id: "order", type: "object" }, "order");
// Remove specific schema by key
ajv.removeSchema("user");
// Remove schemas matching pattern
ajv.removeSchema(/^product/);
// Remove all schemas
ajv.removeSchema();Retrieves a previously compiled validation function by schema key or reference.
/**
* Retrieves compiled validation function by key or reference
* @param keyRef - Schema key or reference
* @returns Compiled validation function or undefined if not found
*/
getSchema<T = unknown>(keyRef: string): ValidateFunction<T> | undefined;Usage Examples:
import Ajv from "ajv";
const ajv = new Ajv();
// Add and compile schema
ajv.addSchema({
$id: "user-schema",
type: "object",
properties: {
name: { type: "string" },
age: { type: "number" }
},
required: ["name"]
}, "user");
// Retrieve compiled validation function
const validateUser = ajv.getSchema("user");
if (validateUser) {
const userData = { name: "Alice", age: 30 };
const valid = validateUser(userData);
if (!valid) {
console.log("Errors:", validateUser.errors);
}
}
// Schema not found returns undefined
const notFound = ajv.getSchema("nonexistent"); // undefinedValidates a schema against its meta-schema to ensure the schema itself is correctly formed.
/**
* Validates a schema against its meta-schema
* @param schema - Schema to validate
* @param throwOrLogErrors - Whether to throw errors or just log them
* @returns true if schema is valid, false otherwise
*/
validateSchema(schema: AnySchema, throwOrLogErrors?: boolean): boolean;Usage Examples:
import Ajv from "ajv";
const ajv = new Ajv();
// Valid schema
const validSchema = {
type: "object",
properties: {
name: { type: "string" }
}
};
console.log(ajv.validateSchema(validSchema)); // true
// Invalid schema (typo in type)
const invalidSchema = {
type: "objct", // typo
properties: {
name: { type: "string" }
}
};
console.log(ajv.validateSchema(invalidSchema)); // false
console.log(ajv.errors); // Schema validation errors
// Throw errors instead of returning false
try {
ajv.validateSchema(invalidSchema, true);
} catch (error) {
console.log("Schema validation failed:", error.message);
}Ajv supports comprehensive schema referencing and resolution:
// Schema with internal references
const schema = {
$id: "https://example.com/person.json",
type: "object",
definitions: {
name: {
type: "string",
minLength: 1
},
positiveInteger: {
type: "integer",
minimum: 0
}
},
properties: {
firstName: { $ref: "#/definitions/name" },
lastName: { $ref: "#/definitions/name" },
age: { $ref: "#/definitions/positiveInteger" }
}
};// Schemas referencing other schemas
ajv.addSchema({
$id: "https://example.com/address.json",
type: "object",
properties: {
street: { type: "string" },
city: { type: "string" },
zipCode: { type: "string" }
}
}, "address");
const personSchema = {
type: "object",
properties: {
name: { type: "string" },
address: { $ref: "address" } // Reference by key
}
};removeSchema() to clear unused schemas when working with many dynamic schemas