Schema Validator
This is a module for validating the input and output of your controllers with an Open API schema. It consists primarily of a decorator and a interceptor that are used to define and validate against the schema respectively. Some helper functions and types are included. See below for details on how to use each.
@Schema decorator
This decorator is used to define the schema to be used for validation of the method handlers in your controllers. You should provide it with the Open API schema for path and HTTP method that corresponds to the handler you are decorating. For example:
import OpenApiSchema from 'contracts';
import { Schema } from '../schema-validator/Schema';
@Controller('pets')
class PetsController {
@Post('/')
@Schema(OpenApiSchema.paths['/pets'].post)
create(@Body() data) {
return this.petsService.create(data);
}
}
ValidateSchemaInterceptor
This interceptor uses the schema defined by the @Schema decorator to validate the request body, request query parameters and response body. This that the data going an and out is correct and type safe. The interceptor will also strip out any properties from those objects that are not defined in your schema. This prevents potentially malicious data coming in to the API and potentially secret data from accidentally leaving the API.
It is intended that the interceptor be used as a global interceptor like so:
import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './AppModule';
import { ValidateSchemaInterceptor } from './modules/schema-validator/ValidateSchemaInterceptor';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(
new ValidateSchemaInterceptor(app.get(Reflector))
);
...
}
bootstrap();
How validation works
This module extracts the JSON schemas out of the Open API schema for each method handler and uses Ajv to validate the request and response payloads. Ajv is configured with the following options:
{
allErrors: true,
strict: true,
parseDate: true,
useDefaults: true,
removeAdditional: 'all'
}
When validating query parameters the coerceTypes: true
option is also provided. This means that there is some deserialisation that occurs through parsing dates, using defaults, coercing types.