Home

Awesome

<div align="center"> <a href="http://nestjs.com/" target="_blank"> <img src="https://nestjs.com/img/logo_text.svg" width="150" alt="Nest Logo" /> </a> </div>

Badges

MIT License GPLv3 License AGPL License

nestjs-DbValidator

This module provides custom database validators using class-validator and typeorm.

Important Note

For Nestjs V8 and below, use version 1.1.3.

Installation

  npm install @youba/nestjs-dbvalidator
  or
  yarn add @youba/nestjs-dbvalidator

Quick Start

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() {}
}

Usage/Examples

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;

All Validators

ParameterDescription
isExistDbCheck if the value is already exist in database
isUniqueDbCheck if the value is unique in database
isLowerDbCheck if the value is lower (example:check client credits)
isBiggerDbCheck if the value is bigger (example:check stock)
ParameterDescription
tableTable nameRequired
columnColumn nameRequired
messageCustom error messageoptional
isArrayCheck in array (works only with isExistDb & isUniqueDb)optional
customType only in V2.0CChanges the type column for validation (Use TYPECOLUMN enums to select a type (NUMBER, STRING))optional

License

MIT