【问题标题】:Inject service into pipe in NestJs在 NestJs 中将服务注入管道
【发布时间】: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 个独立的管道吗?

谢谢。

【问题讨论】:

    标签: node.js nestjs


    【解决方案1】:

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

    【讨论】:

    • 哇,好简单!非常感谢 :) 我的第二个问题(SRP)呢?
    猜你喜欢
    • 2021-11-09
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2022-09-24
    • 2018-11-16
    • 2020-06-23
    • 2019-04-25
    相关资源
    最近更新 更多