npm install @youba/nestjs-dbvalidator
This module has some costume database validators using class-validator and typeorm
To configure the module you need to add typeorm configuration using register()
Example :
// 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 the nestjs-dbvalidator, First validator is "IsExist" to check if the value is already exist in the table, For example:
// src/xModule/x.dto.ts
import { IsExist } from '@youba/nestjs-dbvalidator';
export class StreetDto {
@IsNotEmpty()
name: string;
@IsNotEmpty()
@Validate(IsExist,
[ { table: "city", column: "id"}] )
idcity: number;
...
Ps : In version 1.1.0 you can use IsArray to trait the value as an Array and check if all the values of the array are exists in the table, as an example:
@Validate(IsExist,
[ { table: "city", column: "id", isArray:true}] )
idcities: any;
For the secand validator "IsUnique" is for checking if the value is unique in the table, For example:
// src/xModule/x.dto.ts
import { IsUnique } from '@youba/nestjs-dbvalidator';
export class StreetDto {
@IsNotEmpty()
@Validate(IsUnique,
[ { table: "company", column: "name" }] )
name: string;
...
You can Add 'message' as a parameter to costume your error message
- Implement to these validators to check array of values
- Implement to IsUnique to ignore an x value for the update case
Licensed under the MIT License - see the LICENSE file for details.