【发布时间】:2019-08-24 17:53:27
【问题描述】:
我正在尝试使用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;
}
在the doc 之后,我尝试了几种使用ValidationPipe 的方法,但对我来说没有任何效果。我知道它不起作用,因为尽管请求得到了响应,但当查询为空时,不使用我在 DTO 中为属性limit 编写的默认值50。因此,当查询中没有提供limit 时,limit 的值是未定义的,而它应该是50(即不使用ValidationPipe)。
我的package.json 似乎是正确的:
npm ls class-validator
api-sport@0.0.1 /home/pierre_t/Bureau/dev/ApiSport
└── class-validator@0.9.1
完整的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?
【问题讨论】:
-
您可以添加您的
package.json吗?您的node_modules中似乎有多个版本的class-validator。 -
@KimKern 我用关于我的
package.json的相关信息更新了我的答案 -
请发布完整的
package.json。它可以是您使用的另一个库的子依赖项。 -
你也可以试试
npm ls class-validator -
@KimKern 我添加了整个文件 + npm ls
标签: javascript node.js typescript nestjs class-validator