node.js - 在 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)——所以它可能违反了 SOLID 规则(SRP)——所以我应该将这 3 个角色分成 3 个独立的管道吗?
谢谢。
解决方案
您不能在装饰器中使用类成员,这是打字稿的语言约束。但是,您可以让 Nest 自己使用它来为您完成 DI 工作@Body(SignupPipe)
。Nest 将读取管道的构造函数并查看需要注入的内容。
@Controller("user")
export class UserController {
constructor(private userService: UserService, ) { }
@Post("signup")
async signup(@Body(SignupPipe) createUserDto: CreateUserDto) {
return await this.userService.signup(createUserDto)
}
}
推荐阅读
- python - 为什么我会收到此错误?太多值无法解包(预期 2)
- node.js - 后端脚本处理图像/视频数据时存储在哪里?
- flutter - 如何解决启动时颤动的白屏
- python - How to concatenate two models in keras?
- sql - SQL CTE 不返回总和
- ios - 在 Windows 计算机上为 React Native App 运行 expo build:ios 时出错
- android - 使用 CameraX 或 Camera2 获取相机 ISO / 快门速度
- javascript - UI5 Odata 读取调用同时带有过滤器和 urlParameters
- visual-studio - unity Visual Studio 上的语法着色?
- javascript - 在 Vuejs 中将按钮作为表格列标题传递