Package Exports
- @vvlad1973/data-validator
Readme
@vvlad1973/data-validator
TypeScript library for loading and validating JSON/YAML schemas using AJV with optional logging support.
Features
- Loads all
.json,.jsonc,.yaml,.ymlschemas from a directory - Supports
$reflinks between schemas - Validates data by schema key
- Supports comments (
jsonc) and YAML format - Optional multi-level logging (trace, debug, info, warn, error)
- Compatible with
@botapp/logger-treefor logger binding - Dual-build output (CommonJS and ESM)
- TypeScript path alias resolution
- Comprehensive JSDoc documentation
Installation
npm install @vvlad1973/data-validatorQuick Start
Basic Usage
import DataValidator from '@vvlad1973/data-validator';
const validator = new DataValidator({
schemasDir: './schemas'
});
await validator.isReady();
await validator.validate('user.schema.json', {
name: 'John Doe',
email: 'john@example.com'
});Legacy Constructor (Backward Compatible)
import DataValidator from '@vvlad1973/data-validator';
const validator = new DataValidator('./schemas');
await validator.isReady();With Logger Integration
import DataValidator from '@vvlad1973/data-validator';
import { LoggerTree, LoggerBinder } from '@botapp/logger-tree';
// Create logger tree
const tree = new LoggerTree();
const binder = new LoggerBinder(tree);
// Create validator
const validator = new DataValidator({
schemasDir: './schemas'
});
// Bind logger to validator
binder.bind('app.validator', validator);
// Validator will now log all operations
await validator.validate('user.schema.json', userData);With Custom Logger
import DataValidator, { ILogger } from '@vvlad1973/data-validator';
const customLogger: ILogger = {
trace: (msg, ...args) => console.log('[TRACE]', msg, ...args),
debug: (msg, ...args) => console.log('[DEBUG]', msg, ...args),
info: (msg, ...args) => console.log('[INFO]', msg, ...args),
warn: (msg, ...args) => console.warn('[WARN]', msg, ...args),
error: (msg, ...args) => console.error('[ERROR]', msg, ...args),
};
const validator = new DataValidator({
schemasDir: './schemas',
logger: customLogger
});API Reference
Constructor
new DataValidator(options?: string | DataValidatorOptions)Parameters:
options- Schema directory path (string) or configuration object
DataValidatorOptions:
interface DataValidatorOptions {
schemasDir?: string; // Directory containing schema files
logger?: ILogger; // Optional logger instance
}Methods
isReady(): Promise<boolean>
Checks if schemas are loaded and validator is ready.
const ready = await validator.isReady();
if (ready) {
// Validator is ready to use
}loadSchemasFromDirectory(schemaDir: string): Promise<boolean>
Loads schemas from a directory. Supports .json, .jsonc, .yaml, .yml formats.
await validator.loadSchemasFromDirectory('./custom-schemas');addSchema(schema: object, key: string): void
Adds a schema programmatically.
validator.addSchema({
type: 'object',
properties: {
name: { type: 'string' }
},
required: ['name']
}, 'user');validate(schemaKey: string, data: unknown): Promise<void>
Validates data against a schema. Throws error if validation fails.
try {
await validator.validate('user.schema.json', userData);
console.log('Valid!');
} catch (error) {
console.error('Invalid:', error.message);
}Types
import { DataValidator, DataValidatorOptions, ILogger } from '@vvlad1973/data-validator';ILogger Interface:
interface ILogger {
trace(message?: string, ...optionalParams: unknown[]): void;
debug(message?: string, ...optionalParams: unknown[]): void;
info(message?: string, ...optionalParams: unknown[]): void;
warn(message?: string, ...optionalParams: unknown[]): void;
error(message?: string, ...optionalParams: unknown[]): void;
}Schema Structure
Schemas should be placed in a directory. The package includes example schemas to demonstrate functionality:
schemas/
├── user.schema.json # User validation schema
├── product.schema.yaml # Product schema (YAML format)
├── order.schema.json # Order schema with $ref examples
└── config.schema.jsonc # Config schema (JSON with comments)All matching files (.json, .jsonc, .yaml, .yml) are automatically loaded on initialization. Each schema is registered with its filename (including extension) as the key.
Example Schemas
The package includes example schemas that demonstrate:
- user.schema.json - Basic validation with formats (email, uuid), patterns, and enums
- product.schema.yaml - YAML format support with arrays and nested objects
- order.schema.json - Schema references using
$reffor reusable definitions - config.schema.jsonc - JSONC format with comments for documentation
Logging Levels
When a logger is provided, the validator logs operations at different levels:
- trace - Very detailed info (file parsing, skipped files)
- debug - Operation details (loading schemas, validation start/end)
- info - Major operations (schema loading completed)
- warn - Non-critical issues (directory not found, validation failed)
- error - Critical errors (schema not found, parsing errors)
Example log output:
[DEBUG] Initializing DataValidator { schemasDir: './schemas' }
[TRACE] Files found in schema directory { schemaDir: './schemas', fileCount: 3 }
[DEBUG] Schema loaded successfully { file: 'user.schema.json', key: 'user.schema.json' }
[INFO] Schema loading completed { schemaDir: './schemas', totalFiles: 3, loadedCount: 3 }
[DEBUG] Starting validation { schemaKey: 'user.schema.json' }
[DEBUG] Validation succeeded { schemaKey: 'user.schema.json' }Development
Testing
This project uses Vitest with comprehensive test coverage (96%+).
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch
# Run tests with UI
npm run test:uiTest Coverage:
- Overall: 96.42%
- Statements: 96.42%
- Branches: 91.48%
- Functions: 100%
- Lines: 96.87%
Linting
# Check code quality
npm run lint
# Auto-fix issues
npm run lint:fixBuilding
# Build all (CJS + ESM)
npm run build:all
# Build only CommonJS
npm run build:cjs
# Build only ES modules
npm run build:esmExamples
Complete Example
import DataValidator from '@vvlad1973/data-validator';
import { LoggerTree, LoggerBinder } from '@botapp/logger-tree';
// Setup logger tree
const loggerTree = new LoggerTree();
const loggerBinder = new LoggerBinder(loggerTree);
// Configure logger level
loggerTree.updateParam('app', 'level', 'debug');
// Create validator
const validator = new DataValidator({
schemasDir: './schemas'
});
// Bind logger
loggerBinder.bind('app.validator', validator);
// Wait for schemas to load
await validator.isReady();
// Add custom schema
validator.addSchema({
type: 'object',
properties: {
id: { type: 'string', format: 'uuid' },
email: { type: 'string', format: 'email' },
age: { type: 'number', minimum: 0 }
},
required: ['id', 'email']
}, 'custom-user');
// Validate data
try {
await validator.validate('custom-user', {
id: '123e4567-e89b-12d3-a456-426614174000',
email: 'user@example.com',
age: 25
});
console.log('Data is valid!');
} catch (error) {
console.error('Validation error:', error.message);
}Error Handling
async function validateUserData(userData: unknown) {
const validator = new DataValidator({ schemasDir: './schemas' });
await validator.isReady();
try {
await validator.validate('user.schema.json', userData);
return { valid: true };
} catch (error) {
if (error instanceof Error) {
return {
valid: false,
errors: error.message.split('\n')
};
}
throw error;
}
}TypeScript Support
This package is written in TypeScript and provides full type definitions.
import DataValidator, {
DataValidatorOptions,
ILogger
} from '@vvlad1973/data-validator';
// Type-safe options
const options: DataValidatorOptions = {
schemasDir: './schemas',
logger: myLogger
};
const validator = new DataValidator(options);Build System
The package uses a sophisticated dual-build system:
- CommonJS output in
dist/cjs/ - ESM output in
dist/esm/ - Automatic TypeScript path alias resolution
- Post-build scripts for proper module exports
Both module systems are fully supported and will work correctly in any environment.
Compatibility
- Node.js: 20.x or higher
- TypeScript: 5.x or higher
- Module Systems: CommonJS and ES Modules
- Logger: Compatible with SimpleLogger from @vvlad1973/simple-logger
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Run tests:
npm test - Run linter:
npm run lint - Submit a pull request
Changelog
See CHANGELOG.md for version history.
License
MIT License with Commercial Use