Back to README
Swagger UI
| Versioning
| Validation
| Caching
| Authentication
| Authorization
function enableDynamicAPIValidation(app: INestApplication, options?: ValidationPipeOptions): void
Configuration
// src/main.ts
import { enableDynamicAPIValidation } from 'mongodb-dynamic-api';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// ...
enableDynamicAPIValidation(app); // <- add this line in your main.ts file
await app.listen(3000);
}
The enableDynamicAPIValidation
function allow to configure the pipe validation options for the API globally.
You can also define the pipe validation options in the DynamicApiModule.forFeature
method, either in the controller options,
or in each route object defined in the routes property.
If the options are specified in 2, the options specified in the route will have priority.
// src/users/users.module.ts
import { DynamicApiModule } from 'mongodb-dynamic-api';
import { User } from './user';
@Module({
imports: [
DynamicApiModule.forFeature({
entity: User,
controllerOptions: {
// ...
validationPipeOptions: { // <- in the controller options
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
},
},
routes: [
{
type: 'DuplicateOne',
validationPipeOptions: { transform: true }, // <- in the route options
},
],
}),
],
})
export class UsersModule {}
Usage
Use the Class validator
decorators to validate your class properties.
Let's add IsEmail
decorator to the email
field.
// src/users/user.ts
import { IsEmail } from 'class-validator';
@Schema({ collection: 'users' })
export class User extends BaseEntity {
@ApiProperty()
@Prop({ type: String, required: true })
name: string;
@ApiProperty()
@IsEmail()
@Prop({ type: String, required: true })
email: string;
@ApiPropertyOptional()
@Prop({ type: String })
company?: string;
}
Ok, now if you try to create a new user with an invalid email, you will get a 400 Bad Request
error.
Back to README
Swagger UI
| Versioning
| Validation
| Caching
| Authentication
| Authorization