【问题标题】:NestJS - 'class-validator' shows an error in static class?NestJS - \'class-validator\' 在静态类中显示错误?
【发布时间】:2023-01-10 08:00:58
【问题描述】:

有什么方法可以检查静态类的验证吗?
Decorators are not valid here. ts(1206) 错误仅发生在静态类中。 如何解决?

你们如何在 NestJS 中创建请求和响应 dto? 到目前为止,我一直坚持使用静态类,但不确定这是正确的方法。

import { IsNotEmpty, IsNumber, IsString } from 'class-validator';

export class CreateBoardDto {
  static Request = class {
    @IsString()
    @IsNotEmpty()
    writer: string;

    @IsString()
    @IsNotEmpty()
    title: string;

    @IsString()
    @IsNotEmpty()
    contents: string;
  };

  static Response = class {
    @IsNumber()
    id: number;

    @IsString()
    @IsNotEmpty()
    writer: string;

    @IsString()
    @IsNotEmpty()
    title: string;

    @IsString()
    @IsNotEmpty()
    contents: string;
  };
}

【问题讨论】:

    标签: nestjs decorator class-validator


    【解决方案1】:

    数据对象 (dto) 通常是从请求主体接收到的 data,因此当我们为 POST 请求创建端点时,我们将其主体接收为 dto,例如:

    import {Body,Res,Req} from '@nestjs/common'
    import { Request, Response } from 'express'; 
    import { createBoardDto } from '../dto/file_name'; 
    import { BoardService } from './board.service'; // leave this for now
    
    export class BoardController {
    
    constructor(private readonly boardService: BoardService) {}
    
    @Post('add')
    async addBoard(@Body()dto: CreateBoardDto, @Req() req: Request @Res() res: Response
    ) {
        // your add logic here ... it's better to pass by a service class something like
        return await this.boardService.addBoard(req: Request,res: Response,dto: createBoardDto);
        // you can pass req and res if the Request and Response are needed
    }
    }
    

    这里编译器检查 body 是否是一个有效的类CreateBoardDto

    从你的service类你管理你的逻辑然后你返回一个object作为最终结果(你不需要验证它)你可以返回新创建的板或简单的消息

     {
     message: 'board has been created'
     }
    

    终于在你的createBoardDto 类中:

    import { IsNotEmpty, IsNumber, IsString } from 'class-validator';
    
    export class CreateBoardDto {    
    
    @IsString()
    @IsNotEmpty()
    writer: string;
    
    @IsString()
    @IsNotEmpty()
    title: string;
    
    @IsString()
    @IsNotEmpty()
    contents: string;
    
    }
    

    你不需要任何静态成员

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2019-11-30
      • 2021-10-07
      • 1970-01-01
      • 2020-08-02
      相关资源
      最近更新 更多