typescript 嵌套JS -无法读取未定义的属性

sdnqo3pr  于 2023-01-18  发布在  TypeScript
关注(0)|答案(1)|浏览(205)

我收到错误消息[Nest] 4492 - 06/17/2022,17:59:11 ERROR [ExceptionsHandler]在创建自定义管道以注册电子邮件验证时,无法读取undefined的属性(阅读'findOneByEmail')。
我跟着回答:Email verification with class-validator in nestJS
我错过了什么吗?
//电子邮件-已存在.pipe.ts

import { Injectable } from '@nestjs/common';
import {
  registerDecorator,
  ValidationOptions,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from 'class-validator';

import { UsersService } from 'src/users/users.service';

@ValidatorConstraint({
  name: 'EmailAlreadyExist',
  async: true,
})
@Injectable()
export class EmailAlreadyExistConstraint
  implements ValidatorConstraintInterface
{
  constructor(private readonly usersService: UsersService) {}

  async validate(email: string) {
    return !(await this.usersService.findOneByEmail(email));
  }
}

export function EmailAlreadyExist(validationOptions?: ValidationOptions) {
  return function (object: any, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: EmailAlreadyExistConstraint,
    });
  };
}

//创建用户.dto.ts

@IsNotEmpty()
  @IsEmail()
  @EmailAlreadyExist({
    message: 'the email account already exist',
  })
  email: string;

//用户服务

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { CreateUserDto } from 'src/users/dto/create-user.dto';
import { UpdateUserDto } from 'src/users/dto/update-user.dto';
import { UserEntity } from 'src/users/entities/user.entity';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(UserEntity)
    private usersRepository: Repository<UserEntity>,
  ) {}

  async findOneByEmail(email: string) {
    return await this.usersRepository.findOneBy({ email: email });
  }
}

//用户.模块.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

import { UsersService } from 'src/users/users.service';
import { UsersController } from 'src/users/users.controller';
import { UserEntity } from 'src/users/entities/user.entity';
import { EmailAlreadyExistConstraint } from 'src/users/pipe/email-already-exist.pipe';

@Module({
  imports: [TypeOrmModule.forFeature([UserEntity])],
  controllers: [UsersController],
  providers: [UsersService, EmailAlreadyExistConstraint],
  exports: [UsersService],
})
export class UsersModule {}

根据这里的答案TypeError: Cannot read properties of undefined on NestJS Dependency Injection,我必须添加@Injectable(),但仍然不起作用

h79rfbju

h79rfbju1#

尝试将此添加到您的应用程序中。ts

useContainer(app.select(AppModule), { fallbackOnErrors: true });

source

相关问题