Ajv-based validator service for the Famir platform.
This package provides a shared JSON Schema validation layer built on top of Ajv library.
The package is structured as:
src/ajv-validator.ts - Ajv-based validator implementation.src/index.ts - Package public exports.And exposes the following dependencies:
Validator via VALIDATOR tokennpm install @famir/validator
Example:
import { DIContainer } from '@famir/common'
import { AjvValidator } from '@famir/validator'
// Get the global DI container instance.
const container = DIContainer.getInstance()
// Register dependency:
AjvValidator.register(container)
Example:
import { DIContainer } from '@famir/common'
import { VALIDATOR, Validator } from '@famir/domain'
// Get the global DI container instance.
const container = DIContainer.getInstance()
// Resolve dependency:
const validator = container.resolve<Validator>(VALIDATOR)
The underlying Ajv instance is configured with:
This behavior should be considered when building schemas and validating user input.
Define interface and JSON Schema for object to validate:
import { JSONSchemaType } from '@famir/common'
// Your user interface:
interface User {
name: string
age: number
}
// Your user schema:
const userSchema: JSONSchemaType<User> = {
type: 'object',
required: ['name', 'age'],
properties: {
name: { type: 'string', minLength: 1 },
age: { type: 'integer', minimum: 0 },
},
additionalProperties: false,
} as const
// Add schema to the validator.
validator.addSchema('user', userSchema)
Example:
// Any data to validate
const data: unknown = { name: 'Alice', age: 30 }
// Type-safe guard validation
if (validator.guardSchema<User>('user', data)) {
// TypeScript knows this is User
console.log(data.name)
console.log(data.age)
} else {
console.error('Invalid user data')
}
Example:
// Any data to validate
const data: unknown = { name: 'Bob', age: 25 }
// Type-safe assert validation with exception filter
try {
validator.assertSchema<User>('user', data)
// TypeScript knows this is User
console.log(data.name)
console.log(data.age)
} catch (error) {
if (error instanceof ValidatorError) {
console.warn(error.validateErrors)
} else {
console.error(error)
}
}