Dependency injection with class-validator
I'm submitting a...
[ ] Regression
[ ] Bug report
[ ] Feature request
[x ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.
Current behavior
As mentioned in the documention NestJS is supposed to works well very with class validator, however i'm not successful trying to implement a custom validation class ( https://github.com/typestack/class-validator#custom-validation-classes ) or decorator. This usecase is more than usefull to implement complex validation logic that require injecting services As its a pretty standart usecase, i guess that there is a way to do it, but i'm not able to find it! could be a great addition to the online documentation imo !
Expected behavior
I've tried to add my Validator class as a component but not working. In the class-validator documentation they mentioned that we can register a DI, is this doable with Nest ?
Minimal reproduction of the problem with instructions
@Controller('cars')
export class CarController {
@Get()
public test(@Res() res) {
const dto = new CarInsertDTO();
dto.brand = 'toyota';
validate(dto).then(errs => {
if (errs && errs.length > 0) {
throw new BadRequestException(errs);
}
res.send(200);
});
}
}
export class CarInsertDTO {
@IsString()
public name: string;
@Validate(BrandValidator, { message: 'Invalid brand'})
public readonly strategy;
}
@ValidatorConstraint()
export class BrandValidator implements ValidatorConstraintInterface {
constructor(private readonly brandService: BrandService) {}
validate(brandName: any, args: ValidationArguments) {
// can be a http service , database service or whatever
const brands: string[] = this.brandService.all();
return brands.indexOf(brandName) >= 0;
}
}
Should lead to something like
[Nest] 1736 - 2018-3-26 12:16:38 [ExceptionsHandler] Cannot read property 'all' of undefined TypeError: Cannot read property 'all' of undefined
What is the implementation of your brandService @fmeynard ? How is it imported?
@jmaicaaan
This is only a code sample to illustrate my issue but the brandService is Nest component like
@Component
export class BrandService {
public all() {
return ['toyota','ford']; // in a real world this can a remote call or a database call
}
So my main goal is the use a @Component inside a validator class
I believe nest couldn't find the BrandValidator you are using.. Maybe do you need to add @component also to the BrandValidator to make it injectable and registered to the nest di?
With typeDI module I guess this would work but in nest it can be another work around.
@jmaicaaan As said in the initial request, i've also tried that ( to add the BrandValidator as a @Component ), but its not working, i guess mainly because class-validator don't use Nest DI
It's impossible to inject dependencies into @ValidatorConstraint with Nest.
So is there a better way of doing it? i have similar issue where i need to validate if the user email is existing in the database and i want to use the class-validator, is there any workaround?
@hershko765
The only "workaround" that i have found is very dirty ATM : i've added typedi to my project and i manually register @Components that will be use by class-validator
import { Container } from 'typedi';
// ... others imports
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, validationError: { target: false } }));
const dataSourceModule = app.select(DataSourceModule);
Container.set(DataSourceManager, dataSourceModule.get(DataSourceManager));
Container.set(DataSourceService, dataSourceModule.get(DataSourceService));
await app.listen(config.get('app.port'));
}
According to @kamilmysliwiec 's answer, don't think we have a better way to do that unfortunately
@fmeynard i found a solution, i think its new feature of class-validator called "useContainer", once you do it, class-validator will use nestJS di
main.ts
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';
import {useContainer} from 'class-validator';
import {ValidationPipe} from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
const validationPipe = app
.select(ApplicationModule)
.get(ValidationPipe);
// This will cause class-validator to use the nestJS module resolution,
// the fallback option is to spare our selfs from importing all the class-validator modules to nestJS
useContainer(app.select(ApplicationModule), { fallback: true });
app.useGlobalPipes(validationPipe);
await app.listen(3000);
}
bootstrap();
my constaint: entityExists.constraint.ts
@ValidatorConstraint({ name: 'entityExists', async: false })
@Component()
export class EntityExists implements ValidatorConstraintInterface {
constructor(
@Inject('DbConnectionToken') private readonly connection: Connection,
) {}
async validate(text: string, validationArguments: ValidationArguments) {
const entity = await this.connection.getRepository(validationArguments.constraints[0]).findOneById(text);
return !! entity;
}
defaultMessage(args: ValidationArguments) {
console.log(args);
return 'Entity not exists';
}
}
My dto file:
...
export class CreateCustomerDto {
@Validate(EntityExists, [Customer])
customer_id: number;
....
}
And last step is to add the constraint to your desired module
@Module({
imports: [],
controllers: [
...
],
components: [
Validator,
ValidationPipe,
EntityExists,
...
],
})
export class ApplicationModule implements NestModule {
}
pretty simple, 1 line makes it all work :) you can create your own "ValidationModule" add there all the constraints and stuff, i am just a random lazy guy
Great job @roeehershko! Also, in v5.0.0 you should be able to use the following syntax:
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
useContainer(app, { fallback: true });
await app.listen(3000);
}
bootstrap();
🔥 🔥 🔥 🔥
Hello Nestjs entrepreneurs, in core version : 5.0.0-beta.6 I implement
import { useContainer } from 'class-validator';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
useContainer(app, { fallback: true });
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();
Not work and get this error [Nest] 9880 - 2018-6-4 20:39:27 [ExceptionHandler] Nest cannot find given element (it does not exist in current context)
I would like do dependency injection on a custom validator like this
@ValidatorConstraint({ name: 'isUserAlreadyExist', async: false })
export class IsUserAlreadyExist implements ValidatorConstraintInterface {
constructor(private readonly usersService: UsersService) {}
async validate(text: string) {
const user = await this.usersService.findOne({
email: text,
});
return user ? true : false;
}
}
@yamid-ny Could you share your repository? I'd love to reproduce this issue somewhere.
Yes @kamilmysliwiec https://github.com/yamid-ny/dependency-injection-on-custom-validator thanks !!
http://localhost:3000/auth/register // when register same email user
{
"email": "[email protected]",
"password": "123456"
}
Hi guys, I found a solution for that, you can check my repo: https://github.com/neoteric-eu/nestjs-auth (btw, yesterday I was making a tech-workshops for developers in Gdańsk about how to proper handle authorisation and authentication with nest :smile: ), so, yeah @kamilmysliwiec I spread the love for Nest.js around the world :smile_cat:
@yamid-ny the solution for that in particular is done in two steps, first one:
this.app = await NestFactory.create(AppModule, {
logger: new AppLogger('Nest')
});
useContainer(this.app, {fallbackOnErrors: true});
The {fallbackOnErrors: true} is required, because Nest throw Exception when DI doesn't have required class.
Second thing:
import {ValidatorConstraint, ValidatorConstraintInterface} from 'class-validator';
import {UserService} from './user.service';
import {Injectable} from '@nestjs/common';
@ValidatorConstraint({ name: 'isUserAlreadyExist', async: true })
@Injectable()
export class IsUserAlreadyExist implements ValidatorConstraintInterface {
constructor(protected readonly userService: UserService) {}
async validate(text: string) {
const user = await this.userService.findOne({
email: text
});
return !user;
}
}
IsUserAlreadyExist have to be Injetable and registered in nest module
Like so:
import {Module} from '@nestjs/common';
import { DatabaseModule } from '../database/database.module';
import { UserController } from './user.controller';
import { userProviders } from './user.providers';
import { UserService } from './user.service';
import {IsUserAlreadyExist} from './user.validator';
@Module({
controllers: [UserController],
providers: [...userProviders, IsUserAlreadyExist, UserService],
imports: [DatabaseModule],
exports: [UserService]
})
export class UserModule {
}
Then when I try to do POST /users twice with payload as follow:
{"name": "cojack", "email": "[email protected]", "password": "qwer1234", "roles": ["user"]}
I have got following response:
{"statusCode":422,"error":"Unprocessable Entity","message":[{"property":"email","children":[],"constraints":{"isUserAlreadyExist":"User already exists"}}]}
Hell yeah!
@fmeynard @jmaicaaan @hershko765 @roeehershko - you also guys might be interested how to solve this problem.
Regards ;)
@kamilmysliwiec
useContainer(app, { fallbackOnErrors: true });
and
useContainer(app.select(AppModule), { fallbackOnErrors: true });
behaves different. In first case I've got few errors spitted into the console like this
[Nest] 3442 - 2018-6-12 16:43:51 [ExceptionHandler] Nest cannot find given element (it does not exist in current context)
while container tries to get Validator and MetadataStorage classes. But finally code works correctly, and I got all injected services as expected;
In the second case there are no errors and everything works like a charm.
Can you explain why?
Hello Community !!! How can I validate (all / multiple) Schema fields required ? For example, UserSchema has email, nickname; PostSchema has title ( ... 3 or more fields, 3 or more dependency injections ... ) Currenly I use IsUserAlreadyExist from user.validator, this only validate one field in one schema (email). In a real project We need some like "@Unique" in class-validator ModelDto. You know a solution ?
@kamilmysliwiec I am also interested in why useContainer(app.select(AppModule), { fallbackOnErrors: true }); works perfectly, while useContainer(app, { fallbackOnErrors: true }); throws
[Nest] 3442 - 2018-6-12 16:43:51 [ExceptionHandler] Nest cannot find given element (it does not exist in current context)
Anyways, just wanted to tell you that this project is amazing! Keep up the great work!
@ullalaaron I've explain it in my comment.
@cojack where exactly?
In version 5.1.0, everything works if i write
In bootstrap function:
const app = await NestFactory.create(ApplicationModule);
useContainer(app.select(ApplicationModule), { fallbackOnErrors: true });
await app.listen(config.api.port);
Validator function:
@ValidatorConstraint({ name: 'isUserAlreadyExist', async: true })
@Injectable()
export class IsUserAlreadyExist {
constructor(
@Inject('UserService') private readonly userService: UserService,
) {}
async validate(text: string) {
const user = await this.userService.findOneByEmail(text);
return !user;
}
defaultMessage(args: ValidationArguments) {
return 'User with this email already exists.';
}
}
User entity:
@Entity()
export default class User {
@PrimaryGeneratedColumn('uuid') id: string;
@IsNotEmpty()
@MaxLength(100)
@Validate(IsUserAlreadyExist)
@IsEmail()
@Column({
type: 'varchar',
length: 100,
primary: true,
})
email: string;
}
I use the sample provided and works fine, when i change the service with @InjectRepository the validation
I have the following problem
"Nest can't resolve dependencies of the AnagraficaService (?). Please make sure that the argument at index [0] is available in the AnagraficaService context."
If i remove the Validate all is ok
@ApiModelProperty()
@IsNotEmpty()
@IsEmail()
/*@ValidateIf(o => o.id === undefined || o.id <= 0)
@Validate(IsEmailAlreadyExist, {
message: "Email già utilizzata"
})*/
@Column({ length: 50 })
Email: string;
@Injectable()
export class AnagraficaService extends BaseService<Anagrafica> {
constructor(
@InjectRepository(Anagrafica)
private readonly todoRepository: Repository<Anagrafica>,
) {
super(todoRepository);
}
}
@Module({
imports: [
TypeOrmModule.forFeature([Anagrafica]),
],
controllers: [
... ],
providers: [
AnagraficaService,
IsEmailAlreadyExist,
IsAnagraficaAlreadyExist,
]
})
export class AnagraficaModule {}