Skip to main content

Introduction

Ajv (Another JSON Schema Validator) is a popular, fast JSON Schema validator for Node.js and browser. It validates data against JSON Schema and is commonly used for API request/response validation.

Inversify Validation's Ajv package provides seamless integration with Ajv, allowing you to validate data in your Inversify applications using JSON Schema definitions. The package includes both standard and compiled validation pipes for optimal performance.

Install dependencies

In order to use the package, install it along with Ajv:

npm install ajv @inversifyjs/ajv-validation

Quick Start

Here's a simple example of how to use Ajv validation in your Inversify application:

import {
AjvValidationPipe,
ValidateAjvSchema,
} from '@inversifyjs/ajv-validation';
import { Body, Controller, Post } from '@inversifyjs/http-core';
import { InversifyExpressHttpAdapter } from '@inversifyjs/http-express';
import { InversifyValidationErrorFilter } from '@inversifyjs/http-validation';
import { AnySchema } from 'ajv';
import Ajv from 'ajv';
import { Container } from 'inversify';

const container: Container = new Container();
const ajv: Ajv = new Ajv();

// Create HTTP adapter
const adapter: InversifyExpressHttpAdapter = new InversifyExpressHttpAdapter(
container,
);

// Register global AJV validation pipe
adapter.useGlobalPipe(new AjvValidationPipe(ajv));
adapter.useGlobalFilters(InversifyValidationErrorFilter);

// Define a JSON schema
const userSchema: AnySchema = {
additionalProperties: false,
properties: {
age: { minimum: 0, type: 'number' },
email: { format: 'email', type: 'string' },
name: { minLength: 1, type: 'string' },
},
required: ['name', 'email'],
type: 'object',
};

interface User {
age?: number;
email: string;
name: string;
}

@Controller('/users')
export class UserController {
@Post('/')
public createUser(@ValidateAjvSchema(userSchema) @Body() user: User): string {
return `Created user: ${user.name}`;
}
}

This example sets up Ajv validation for a user creation endpoint, ensuring that the request body matches the defined JSON schema before the controller method executes.