将服务注入NestJs中的管道

时间:2020-07-23 19:47:28

标签: 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上下文中可用。

我的管道正确吗?我不确定,因为它做一些事情(验证密码/重复,检查acc是否存在,对密码加密)-可能破坏了SOLID规则(SRP)-所以我应该将这3个角色分成3个单独的管道吗? / p>

谢谢。

1 个答案:

答案 0 :(得分:3)

您不能在装饰器内部使用类成员,这是打字稿的语言限制。但是,您可以通过单独使用@Body(SignupPipe)来使Nest帮您完成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)
    }
}