我正在尝试使用ValidationPipe
,但无论我如何编写代码,我在发送请求时都会收到以下警告:No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies
。
我的路线看起来像这样:
@Get()
@UsePipes(new ValidationPipe({ transform: true }))
async findAll(@Query() queryDto: QueryDto) {
return await this.myService.findAll(queryDto);
}
我的DTO看起来像这样:
export class queryDto
{
@ApiModelProperty({
description: 'Maximum number of results',
type: Number,
example: 50,
default: 50,
required: false
})
readonly limit: number = 50;
}
我尝试使用ValidationPipe
几种方式,跟随the doc,但没有什么对我有用。我知道它不起作用,因为虽然请求获得了响应,但是当我的查询为空时,我在DTO中为属性limit
写的默认值50
不会被使用。因此,当查询中没有提供limit
时,limit
的值是未定义的,而它应该是50
(这意味着不使用ValidationPipe
)。
我的package.json
似乎是正确的:
npm ls class-validator
[email protected] /home/pierre_t/Bureau/dev/ApiSport
└── [email protected]
完整的package.json
:
{
"name": "api-sport",
"version": "0.0.1",
"description": "",
"author": "",
"license": "MIT",
"scripts": {
"build": "tsc -p tsconfig.build.json",
"format": "prettier --write \"src/**/*.ts\"",
"start": "ts-node -r tsconfig-paths/register src/main.ts",
"start:dev": "nodemon",
"start:debug": "nodemon --config nodemon-debug.json",
"start:prod": "pm2 start ./src/main.js --no-daemon",
"lint": "tslint -p tsconfig.json -c tslint.json",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^6.0.5",
"@nestjs/core": "^6.0.5",
"@nestjs/platform-express": "^6.0.5",
"@nestjs/swagger": "^3.0.1",
"@nestjs/typeorm": "^6.0.0",
"@types/lodash": "^4.14.123",
"class-transformer": "^0.2.0",
"class-validator": "^0.9.1",
"dotenv": "^7.0.0",
"hbs": "^4.0.3",
"mysql": "^2.16.0",
"pm2": "^3.4.1",
"reflect-metadata": "^0.1.12",
"rimraf": "^2.6.2",
"rxjs": "^6.3.3",
"swagger-ui-express": "^4.0.2",
"typeorm": "^0.2.16"
},
"devDependencies": {
"@nestjs/testing": "^6.0.5",
"@types/express": "^4.16.0",
"@types/jest": "^23.3.13",
"@types/node": "^10.14.4",
"@types/supertest": "^2.0.7",
"jest": "^23.6.0",
"nodemon": "^1.18.9",
"prettier": "^1.15.3",
"supertest": "^3.4.1",
"ts-jest": "^23.10.5",
"ts-node": "^7.0.1",
"tsconfig-paths": "^3.7.0",
"tslint": "5.12.1",
"typescript": "^3.4.1"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
为什么我会收到此消息,如何使用ValidationPipe
?
这是因为你使用class-validator
但没有任何验证,请参阅此issue:
基本上,它警告您在存储中没有任何元数据,这意味着您没有使用类验证器中的任何装饰器。这意味着您不执行任何验证,因此您应该将
validate: false
选项传递给buildSchema
以禁用自动验证。
我不确定你是否可以对nest的ValidationPipe
进行验证,但是你也可以在你的dto中添加一个断言(如果有意义的话),例如:
import { Min } from 'class-validator';
export class QueryDto {
@Min(1)
readonly limit: number = 50;
}
顺便说一下:由于你的@Query
只有字符串属性,你可能想要将你的limit
从string
变换为number
。看看这个answer。