gpt4 book ai didi

typescript - 如何使用类验证器向nestjs中的验证器约束接口(interface)注入(inject)服务?

转载 作者:行者123 更新时间:2023-12-03 20:11:01 25 4
gpt4 key购买 nike

我正在尝试将我的用户服务注入(inject)我的验证器约束界面,但它似乎不起作用:

import { ValidatorConstraintInterface, ValidatorConstraint, ValidationArguments, registerDecorator, ValidationOptions } from "class-validator";
import { UsersService } from './users.service';

@ValidatorConstraint({ async: true })
export class IsEmailAlreadyInUseConstraint implements ValidatorConstraintInterface {
constructor(private usersService: UsersService) {
console.log(this.usersService);
}
validate(email: any, args: ValidationArguments) {
return this.usersService.findUserByEmail(email).then(user => {
if (user) return false;
return true;
});
return false;
}

}

但是,由于 usersService 被记录为空,我无法访问它的方法。

对这个问题有任何见解吗?

最佳答案

对于那些可能遭受此问题的人:

如果要将依赖项注入(inject)自定义验证器约束类,则 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. 将约束作为提供者注入(inject)到您的模块中,并确保您打算注入(inject)到约束中的服务也可用于模块级别:
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 {
}

关于typescript - 如何使用类验证器向nestjs中的验证器约束接口(interface)注入(inject)服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60062318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com