简体   繁体   中英

NestJS - 'class-validator' shows an error in static class?

Is there any way to check validation with static class?
The Decorators are not valid here. ts(1206) Decorators are not valid here. ts(1206) error occurs only with static class. How to fix it?

And how you guys create request and response dto in NestJS? so far, I've sticked with static class but not sure this is correct way.

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:

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 .

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

 {
 message: 'board has been created'
 }

finally in your 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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