枫叶秋林 2 anni fa
parent
commit
4af67d9dad
4 ha cambiato i file con 37 aggiunte e 5 eliminazioni
  1. 1 0
      package.json
  2. 24 0
      src/Validate.pipe.ts
  3. 7 5
      src/main.ts
  4. 5 0
      yarn.lock

+ 1 - 0
package.json

@@ -29,6 +29,7 @@
     "@nestjs/platform-express": "^9.0.0",
     "@prisma/client": "4.7.0",
     "argon2": "^0.30.2",
+    "class-transformer": "^0.5.1",
     "class-validator": "^0.13.2",
     "passport": "^0.6.0",
     "passport-jwt": "^4.0.0",

+ 24 - 0
src/Validate.pipe.ts

@@ -0,0 +1,24 @@
+import { ArgumentMetadata, BadRequestException, Injectable, PipeTransform } from '@nestjs/common'
+import { plainToInstance } from 'class-transformer'
+import { validate } from 'class-validator'
+
+@Injectable()
+export class ValidatePipe implements PipeTransform {
+  async transform(value: any, metadata: ArgumentMetadata) {
+    const { metatype } = metadata
+    //前台提交的表单数据没有类型,使用 plainToClass 转为有类型的对象用于验证
+    const object = plainToInstance(metatype, value)
+    //根据 DTO 中的装饰器进行验证
+    const errors = await validate(object)
+    if (errors.length) {
+      let res = errors.map((value) => {
+        return {
+          name: value?.property,
+          msg: Object.values(value.constraints),
+        }
+      })
+      throw new BadRequestException(res)
+    }
+    return value
+  }
+}

+ 7 - 5
src/main.ts

@@ -1,8 +1,10 @@
-import { NestFactory } from '@nestjs/core';
-import { AppModule } from './app.module';
+import { NestFactory } from '@nestjs/core'
+import { AppModule } from './app.module'
+import { ValidatePipe } from './Validate.pipe'
 
 async function bootstrap() {
-  const app = await NestFactory.create(AppModule);
-  await app.listen(3000);
+  const app = await NestFactory.create(AppModule)
+  app.useGlobalPipes(new ValidatePipe())
+  await app.listen(3000)
 }
-bootstrap();
+bootstrap()

+ 5 - 0
yarn.lock

@@ -1819,6 +1819,11 @@ cjs-module-lexer@^1.0.0:
   resolved "https://mirrors.cloud.tencent.com/npm/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz#9f84ba3244a512f3a54e5277e8eef4c489864e40"
   integrity sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA==
 
+class-transformer@^0.5.1:
+  version "0.5.1"
+  resolved "https://mirrors.cloud.tencent.com/npm/class-transformer/-/class-transformer-0.5.1.tgz#24147d5dffd2a6cea930a3250a677addf96ab336"
+  integrity sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==
+
 class-validator@^0.13.2:
   version "0.13.2"
   resolved "https://mirrors.cloud.tencent.com/npm/class-validator/-/class-validator-0.13.2.tgz#64b031e9f3f81a1e1dcd04a5d604734608b24143"