@db-validator/typeorm
v1.0.0
Published
Database validation decorators for NestJS with TypeORM - UniqueDB and IsExists validators
Maintainers
Readme
@redis-nest/db-validator
Database validation decorators for NestJS with TypeORM. This library provides custom validators to check for uniqueness and existence of values in your database.
Installation
npm install @redis-nest/db-validatorPeer Dependencies
This library requires the following peer dependencies (already installed in your NestJS project):
@nestjs/common(^10.0.0 || ^11.0.0)@nestjs/typeorm(^10.0.0 || ^11.0.0)class-validator(^0.14.0)typeorm(^0.3.0)
Setup
1. Import the ValidatorsModule in your AppModule
import { Module } from '@nestjs/common';
import { ValidatorsModule } from '@redis-nest/db-validator';
@Module({
imports: [
// ... other modules
ValidatorsModule,
],
})
export class AppModule {}2. Use the validators in your DTOs
import { UniqueDB, IsExists } from '@redis-nest/db-validator';
import { User } from '../entities/user.entity';
import { Role } from '../entities/role.entity';
export class CreateUserDto {
@UniqueDB(User, 'email', { message: 'Email already exists' })
@IsEmail()
@IsNotEmpty()
email: string;
}
export class UpdateUserDto {
@IsExists(Role, 'id', { message: 'Role does not exist' })
@IsNotEmpty()
roleId: number;
}Validators
@UniqueDB(entity, fieldName, options?)
Validates that a field value is unique in the database.
Parameters:
entity: The TypeORM entity classfieldName: The field name to check for uniquenessoptions: Optional validation options (e.g.,{ message: 'Custom error message' })
Example:
@UniqueDB(User, 'email')
email: string;@IsExists(entity, fieldName, options?)
Validates that a field value exists in the database.
Parameters:
entity: The TypeORM entity classfieldName: The field name to check for existenceoptions: Optional validation options (e.g.,{ message: 'Custom error message' })
Example:
@IsExists(Role, 'id')
roleId: number;How It Works
- The
ValidatorsModuleregisters aValidationServicethat uses TypeORM's DataSource to query the database. - The validators use this service to check for uniqueness or existence.
- If the service is not available, the validators fall back to using
getRepository()directly.
License
MIT
