对于那些可能遭受此问题的人:
如果要将依赖项注入自定义验证器约束类,则 class-validator 要求您使用服务容器。来自:https ://github.com/typestack/class-validator#using-service-container
import {useContainer, Validator} from "class-validator";
// do this somewhere in the global application level:
useContainer(Container);
因此我们需要将用户容器功能添加到全局应用程序级别。
1. 在 app 声明后将以下代码添加到您的 main.ts 引导函数中:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
useContainer(app.select(AppModule), { fallbackOnErrors: true });
...}
{fallbackOnErrors: true} 是必需的,因为当 DI 没有所需的类时 Nest 会抛出异常。
2. 将 Injectable() 添加到您的约束中:
import {ValidatorConstraint, ValidatorConstraintInterface} from 'class-validator';
import {UsersService} from './user.service';
import {Injectable} from '@nestjs/common';
@ValidatorConstraint({ name: 'isUserAlreadyExist', async: true })
@Injectable() // this is needed in order to the class be injected into the module
export class IsUserAlreadyExist implements ValidatorConstraintInterface {
constructor(protected readonly usersService: UsersService) {}
async validate(text: string) {
const user = await this.usersService.findOne({
email: text
});
return !user;
}
}
3. 将约束作为提供者注入到您的模块中,并确保您打算注入到约束中的服务也可用于模块级别:
import {Module} from '@nestjs/common';
import { UsersController } from './user.controller';
import { UsersService } from './user.service';
import { IsUserAlreadyExist } from './user.validator';
@Module({
controllers: [UsersController],
providers: [IsUserAlreadyExist, UsersService],
imports: [],
exports: []
})
export class UserModule {
}