This module provides custom database validators using class-validator and typeorm.
For Nestjs V8 and below, use version 1.1.3.
npm install @youba/nestjs-dbvalidator
or
yarn add @youba/nestjs-dbvalidator
To configure the module, you need to add the typeorm configuration using register()
// src/xModule/x.module.ts
//...
import { DbValidatorsModule } from '@youba/nestjs-dbvalidator';
import { ConfigModule, ConfigService } from '@nestjs/config';
@Module({
imports: [
DbValidatorsModule.register({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'demo',
}),
],
providers: [StreetService],
controllers: [StreetController],
})
export class StreetModule {
constructor() {}
}
Now you can use nestjs-dbvalidator. The first validator is isExistDb, which checks if the value already exists in the table. For example:
// src/xModule/x.dto.ts
import { isExistDb } from '@youba/nestjs-dbvalidator';
export class StreetDto {
@IsNotEmpty()
name: string;
@IsNotEmpty()
@isExistDb({ table: 'user', column: 'firstName' })
idcity: number;
...
Note: In version 1.1.0, you can use IsArray to treat the value as an array and check if all the values of the array exist in the table. For example::
@isExistDb({ table: 'user', column: 'firstName', isArray:true })
idcities: any;
Parameter | Description | |
---|---|---|
isExistDb |
Check if the value is already exist in database | |
isUniqueDb |
Check if the value is unique in database | |
isLowerDb |
Check if the value is lower (example:check client credits) | |
isBiggerDb |
Check if the value is bigger (example:check stock) |
Parameter | Description | |
---|---|---|
table |
Table name | Required |
column |
Column name | Required |
message |
Custom error message | optional |
isArray |
Check in array (works only with isExistDb & isUniqueDb) | optional |
customType only in V2.0 |
CChanges the type column for validation (Use TYPECOLUMN enums to select a type (NUMBER, STRING)) | optional |