TypeScript - Nest JS - ไม่สามารถอ่านคุณสมบัติของค่าที่เป็น undefined
ฉันได้รับข้อความแสดงข้อผิดพลาด [Nest] 4492 - 17/06/2022, 17:59:11 ERROR [ExceptionsHandler] ไม่สามารถอ่านคุณสมบัติของค่า undefined (การอ่าน 'findOneByEmail') เมื่อสร้าง pipe แบบกำหนดเองสำหรับการตรวจสอบอีเมลที่ลงทะเบียน
ฉันทำตามคำตอบ: การยืนยันอีเมลด้วย class-validator ใน 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,
});
};
}
// สร้าง-user.dto.ts
@IsNotEmpty()
@IsEmail()
@EmailAlreadyExist({
message: 'the email account already exist',
})
email: string;
// users.service.ts
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 });
}
}
// users.module.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: ไม่สามารถอ่านคุณสมบัติของ undefined บน NestJS Dependency Injection ฉันต้องเพิ่ม @Injectable() แต่ก็ยังใช้งานไม่ได้
คำตอบ #1
ลองเพิ่มสิ่งนี้ในไฟล์ app.ts ของคุณ
useContainer(app.select(AppModule), { fallbackOnErrors: true });
แหล่งที่มา
คำตอบ #2
เพิ่มโค้ดด้านล่างลงในฟังก์ชัน bootstrap ในไฟล์ main.ts ของคุณ
useContainer(app.select(AppModule), {
fallbackOnErrors: true
});
