NestJS-根据请求形状以不同方式验证/序列化

时间:2020-01-12 17:26:03

标签: nestjs

我需要基于主体上的“状态”属性来验证一个可能具有3种不同形状的请求,序列化也需要

我该怎么做?

请求正文示例:

{ "status" : "training", "trainingSetId": "dijado389828", "fileData": { "fileUrl": someurl, "nRows": 4000" } }

{ "status" : "test", "testSetId": "ddadfaax344x", "someOtherProp": "idk", "fileData": { "fileUrl": someurl, "nRows": 4000", "predictionFileUrl": someotherurl } }

我可以为每种请求类型创建一个类,但是我将如何有条件地使用其中一种?

1 个答案:

答案 0 :(得分:0)

您可以将https://docs.nestjs.com/pipes#object-schema-validation用于以下用途:

import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';

@Injectable()
export class JoiValidationPipe implements PipeTransform {
  constructor(private readonly schema: Object) {}

  transform(value: any, metadata: ArgumentMetadata) {
    const { error } = this.schema.validate(value);
    if (error) {
      throw new BadRequestException('Validation failed');
    }
    return value;
  }
}

其中schema可以在其他文件中定义,并且在控制器中使用Pipe时可以作为参数传递,例如模式对象:

export const schema = Joi.object({
    status: Joi.string().valid('training', 'test'),
    rest_keys: Joi.any()
})
    .when(Joi.object({ status: Joi.exist() }).unknown(), {
        then: Joi.object({
            rest_key: Joi.valid('some_value or required')
        }),
        otherwise: Joi.object({
            a: Joi.valid('similar as above')
        })
});

您可以在https://hapi.dev/family/joi/api/?v=17.0.2#anywhencondition-options

上阅读有关使用Joi进行条件验证的更多信息。
相关问题