将服务注入NestJs中的管道 [英] Inject service into pipe in NestJs
本文介绍了将服务注入NestJs中的管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试向管道中注入服务。我在控制器POST方法中使用管道(signupPipe)。
// signup.pipe.ts
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { UserService } from './user.service'
@Injectable()
export class SignupPipe implements PipeTransform<any> {
constructor(private userService: UserService) { }
async transform(value: any) {
// validate password
const areTheSame = this.validatePassword(value.password, value.passwordRepeat);
if (!areTheSame) {
throw new BadRequestException("Password are not the same.");
}
// check if account exists
const isExists = await this.userService.findOne(value.email)
if (isExists) {
throw new BadRequestException("Account with provided email already exists.");
}
// create encrypted password
const signupData = {...value}
signupData.password = await bcrypt.hash(value.password, 10)
return signupData
}
private validatePassword(password: string, passwordRepeat: string): boolean {
return password === passwordRepeat
}
}
我的控制器:
@Controller("user")
export class UserController {
constructor(private userService: UserService, private signupPipe: SignupPipe) { }
@Post("signup")
async signup(@Body(this.signupPipe) createUserDto: CreateUserDto) {
return await this.userService.signup(createUserDto)
}
}
用户模块:
@Module({
imports: [MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])],
controllers: [UserController],
providers: [
UserService
],
exports: [UserService]
})
export class UserModule { }
如何正确插入包含DI注入的另一个服务的管道? 现在无法工作,错误:
Nest无法解析UserController(UserService, ?)。请确保索引[1]处的参数SignupPipe值为 在UserModule上下文中可用。
我的烟斗正确吗?我不确定,因为它做了几件事(验证PWD/Repeat、检查acc是否存在、加密PWD)-所以它可能违反了可靠规则(SRP)-所以我应该将这3个角色拆分到3个独立的管道中吗?
谢谢。
推荐答案
您不能在修饰符中使用类成员,这是TypeScript的语言约束。但是,您可以让Nest自己使用@Body(SignupPipe)
为您完成DI工作。Nest将读取管道的构造函数,并查看需要向其注入的内容。
@Controller("user")
export class UserController {
constructor(private userService: UserService, ) { }
@Post("signup")
async signup(@Body(SignupPipe) createUserDto: CreateUserDto) {
return await this.userService.signup(createUserDto)
}
}
这篇关于将服务注入NestJs中的管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文