我正在尝试在 nestjs 中使用 DTO 验证一组对象。我试过了,但数据没有得到验证。我试图搜索很多,但没有得到任何答案。 这些是我的文件:
trivia.controller.ts 文件
import { Controller, Post, Body, ParseArrayPipe } from '@nestjs/common';
import { LoggerService } from '../logger/logger.service';
import { TriviaService } from './trivia.service';
import { PostTriviaScoreDto } from './dto/post-trivia-score.dto';
@Controller('trivia')
export class TriviaController {
constructor(private readonly logger: LoggerService, private readonly triviaService: TriviaService) {}
@Post('score')
postTriviaScore(@Body(new ParseArrayPipe({ items: PostTriviaScoreDto })) postTriviaScoreDto: PostTriviaScoreDto) {
this.logger.info('Trivia Controller : postTriviaScore : start');
return this.triviaService.postTriviaScore(postTriviaScoreParamsDto, postTriviaScoreDto);
}
}
trivia.service.ts 文件
import { LoggerService } from '../logger/logger.service';
import { PostTriviaScoreDto } from './dto/post-trivia-score.dto';
@Injectable()
export class TriviaService {
constructor(
private readonly logger: LoggerService,
) {}
postTriviaScore(allPlayersTriviaScore: PostTriviaScoreDto) {
this.logger.info('Trivia Service : postTriviaScore : start');
console.log('allPlayersScore ', allPlayersTriviaScore);
}
}
post-trivia-score.dto.ts 文件
import { Type } from 'class-transformer';
import { IsNotEmpty, IsUUID, ValidateNested } from 'class-validator';
class TriviaScore {
@IsNotEmpty()
@IsUUID()
question_id: string;
@IsNotEmpty()
@IsUUID()
selected_option_id: string;
@IsNotEmpty()
answered_in_time: number;
}
export class PostTriviaScoreDto {
@ValidateNested({ each: true })
@Type(() => TriviaScore)
items: TriviaScore[];
}
我的 JSON 结构
[
{
"question_id": "088f1344-061e-4bcc-966f-512775f1f082",
"selected_option_id": "72305e08-fedd-49b1-adb9-1dd92c88f4db",
"answered_in_time": 2
}
]
此处未验证属性。即使我在 answers_in_time 字段中传递一个字符串,它也会接受正文并且不会抛出错误,或者如果我在任何字段中传递空字符串,它也会接受请求正文。
如果你们知道解决方案,请帮助我,因为我真的卡在这里了。