Is it possible to inject execution context or access current request in nestJs (class-validator => custom validator) ?
import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';
import { Injectable } from '@nestjs/common';
import { Connection } from 'typeorm';
import { InjectConnection } from '@nestjs/typeorm';
@ValidatorConstraint({ name: 'modelExistsConstraint', async: true })
@Injectable()
export class ModelExistsConstraint implements ValidatorConstraintInterface {
constructor(
@InjectConnection('default') private readonly connection: Connection,
) {
}
async validate(value: string, validationArguments: ValidationArguments) {
// here need request or execution context;
// const test = this.context.switchToHttp().getRequest();
const model = await this.connection
.getRepository(validationArguments.constraints[0])
.findOne({ where: { [validationArguments.property]: value } });
return !model;
}
defaultMessage(args: ValidationArguments) {
return `Model with "${args.property}" - "${args.value}" already exists`;
}
}
ValidationPipe
? – Dieselelectric