首页 > 解决方案 > 在 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 个独立的管道吗?

谢谢。

标签: node.jsnestjs

解决方案


您不能在装饰器中使用类成员,这是打字稿的语言约束。但是,您可以让 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)
    }
}

推荐阅读