UNPKG

apiveritas

Version:

Lightweight CLI tool for consumer-driven API contract testing via JSON schema and payload comparisons.

59 lines (58 loc) 2.18 kB
"use strict"; /** * @file SchemaValidator.ts * @author Mario Galea * @description * A wrapper around the Ajv JSON Schema validator. Provides functionality to validate * data against a given schema and retrieve detailed error messages. */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SchemaValidator = void 0; const ajv_1 = __importDefault(require("ajv")); /** * Class responsible for validating JSON data against a provided JSON Schema using Ajv. */ class SchemaValidator { /** * Initializes the Ajv validator with options to collect all errors * and to allow loose schema rules (strict mode disabled). */ constructor() { this.lastErrors = []; this.ajv = new ajv_1.default({ allErrors: true, strict: false }); } /** * Validates the provided data against the given JSON Schema. * * @param schema - The JSON Schema object to validate against. * @param data - The data to be validated. * @returns `true` if validation passes, `false` otherwise. */ validate(schema, data) { const validate = this.ajv.compile(schema); const valid = validate(data); this.lastErrors = validate.errors || []; return valid; } /** * Returns an array of human-readable validation error messages. * * @returns An array of strings describing where and why validation failed. */ getErrors() { return this.lastErrors.map((err) => { const instancePath = err.instancePath || '#'; const keyword = err.keyword; const message = err.message ?? 'Unknown error'; const prop = err.params.additionalProperty; if (keyword === 'additionalProperties' && prop) { return `Unexpected property "${prop}" at ${instancePath}. Schema does not allow additional properties.`; } return `Schema validation error at ${instancePath}: ${message}`; }); } } exports.SchemaValidator = SchemaValidator;