Skip to main content

@ditsmod/openapi-validation

To provide automatic metadata-based validation in Ditsmod applications for OpenAPI, you can use the @ditsmod/openapi-validation module. Under the hood, this module has an integration with the ajv library, which directly performs the validation just mentioned.

Currently, automatic validation only works for HTTP requests that have a media type of application/json and do not refer to Reference Object. Automatic validation works for parameters in:

  • path
  • query
  • cookie
  • header
  • request's body.

Installation

After you create OpenAPI documentation, you need to import two modules for automatic validation based on it:

npm i @ditsmod/openapi-validation @ditsmod/i18n

Enable validation and set options

To enable automatic validation in a specific module, it is enough to import ValidationModule there. You can also pass ValidationOptions and AJV_OPTIONS:

import { featureModule, Providers, Status } from '@ditsmod/core';
import { ValidationModule, ValidationOptions, AJV_OPTIONS } from '@ditsmod/openapi-validation';
import { Options } from 'ajv';

@featureModule({
imports: [ValidationModule],
providersPerApp: [
...new Providers()
.useValue<ValidationOptions>(ValidationOptions, { invalidStatus: Status.UNPROCESSABLE_ENTRY })
.useValue<Options>(AJV_OPTIONS, { allErrors: true })
]
// ...
})
export class SomeModule {}

Substituting of validation interceptors

The ParametersInterceptor and RequestBodyInterceptor classes are responsible for validating the request body and request parameters. They can be substituted in the providersPerReq array at the module or controller level:

import { featureModule } from '@ditsmod/core';
import { ParametersInterceptor } from '@ditsmod/openapi-validation';

import { MyInterceptor } from './my.interceptor.js';

@featureModule({
// ...
providersPerReq: [
{ token: ParametersInterceptor, useClass: MyInterceptor }
]
// ...
})
export class SomeModule {}

Before writing your interceptor for validation, you can first review how is written, for example ParametersInterceptor.