简体   繁体   English

NestJS - 'class-validator' 在 static class 中显示错误?

[英]NestJS - 'class-validator' shows an error in static class?

Is there any way to check validation with static class?有没有办法用 static class 检查验证?
The Decorators are not valid here. ts(1206) Decorators are not valid here. ts(1206) Decorators are not valid here. ts(1206) error occurs only with static class. How to fix it? Decorators are not valid here. ts(1206)错误仅发生在 static class。如何解决?

And how you guys create request and response dto in NestJS?你们如何在 NestJS 中创建请求和响应 dto? so far, I've sticked with static class but not sure this is correct way.到目前为止,我一直坚持使用 static class 但不确定这是正确的方法。

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;
  };
}

在此处输入图像描述

data object (dto) is usually the data recived from the request body, so when we create an end-point for a POST request we recive its body as dto , example: data object (dto) 通常是从请求主体接收到的数据,所以当我们为 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
}
}

here the compiler check if body is a valid class CreateBoardDto .这里编译器检查 body 是否是有效的 class CreateBoardDto

and from your service class you manage your logic and then you return an object as final result (you don't need to validate it) you can return the new created board or a simple message从你的service class 你管理你的逻辑然后你返回一个object作为最终结果(你不需要验证它)你可以返回新创建的板或一条简单的消息

 {
 message: 'board has been created'
 }

finally in your createBoardDto class:最后在你的createBoardDto class 中:

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

export class CreateBoardDto {    

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

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

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

}

you don't need any static members你不需要任何 static 成员

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM