【发布时间】:2020-08-11 08:23:20
【问题描述】:
我正在尝试在管道中注入服务。我在控制器中使用管道 (signupPipe),POST 方法。
// 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)——所以它可能违反了 SOLID 规则(SRP)——所以我应该将这 3 个角色分成 3 个独立的管道吗?
谢谢。
【问题讨论】: