ljlm0402 / typescript-express-starter

📘 Quick and Easy TypeScript Express Starter
http://npm.im/typescript-express-starter
MIT License
2.72k stars 420 forks source link

Bug of 'class-validator' while using @ValidateNested() #203

Closed Cha-Shao closed 1 year ago

Cha-Shao commented 1 year ago

Describe the Bug (버그 설명)

An error will be thrown when Dto uses ValidateNested

Version to Reproduce (현재 사용한 버전)

Steps to Reproduce (재현 순서)

create a dto

dtos/accounts.dto.ts

class LinksDto {
  @IsString()
  @MaxLength(39)
  public github: string;
  @IsString()
  @MaxLength(39)
  public youtube: string;
}

export class AccountDto {
  @IsString()
  public username: string;
  @ValidateNested()
  public links: LinksDto ;
}

routes/accounts.route.ts

this.router.post(`${this.path}links`, authMiddleware, validationMiddleware(AccountDto, 'body'), this.accountsController.links);

Expected Behavior (예상 동작)

Check the validity of the request and return an error or continue

Actual Behavior (실제 동작)

throw an error and crashed

2023-03-23 18:33:54 error: uncaughtException: Cannot convert undefined or null to object
TypeError: Cannot convert undefined or null to object
    at Function.values (<anonymous>)
    at D:\Projects\javascript\example\src\middlewares\validation.middleware.ts:17:71
    at Array.map (<anonymous>)
    at D:\Projects\javascript\example\src\middlewares\validation.middleware.ts:17:32
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

Additional Context (추가 사항)

I think the problem is here

middlewares/validation.middleware.ts

validate(plainToClass(type, req[value]), { skipMissingProperties, whitelist, forbidNonWhitelisted }).then((errors: ValidationError[]) => {
  if (errors.length > 0) {
    const message = errors.map((error: ValidationError) => Object.values(error.constraints)).join(', ');
    next(new HttpException(400, message.toString()));
  } else {
    next();
  }
});

Object.values(error.constraints)

Because an error occurred in a nested object, the outermost error does not contain constraints

Capture screen (캡쳐 화면)

Cha-Shao commented 1 year ago

i got this response if I use

const message = errors
  .map((error: ValidationError) =>
    error.constraints ? Object.values(error.constraints) : error.children.map((error: ValidationError) => Object.values(error.constraints)),
  )
  .join(', ');

property github should not exist,property youtube should not exist