深圳幻海软件技术有限公司 欢迎您!

实现Nest中参数的联合类型校验

2023-02-28

场景概述我们在进行接口开发时,客户端需要传入一个名为text的字段,它可能是string类型或Array<Object>类型(在TS中我们把这种关系称之为联合类型),class-validator库中提供了相关的校验注解,那把他们写在一起能否完成相关的校验呢,如下所示:复制exportc

场景概述

我们在进行接口开发时,客户端需要传入一个名为text的字段,它可能是string类型或Array<Object>类型(在TS中我们把这种关系称之为 联合类型 ),class-validator库中提供了相关的校验注解,那把他们写在一起能否完成相关的校验呢,如下所示:

export class AppDto {
 @ApiProperty({ example: "2022年4月20日修改", description: "备注" })
  @IsString()
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => TextObjDto)
  public text!: string | Array<TextObjType>; 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

TextObjDto的代码如下所示:

export class TextObjDto {
  @ApiProperty({ example: "修复了一些bug", description: "内容" })
  @IsString()
  content!: string;
  @ApiProperty({ example: "2022-04-20 07:52", description: "创建时间" })
  @IsString()
  createTime?: string;
  @ApiProperty({ example: true, description: "是否为新功能标识" })
  @IsBoolean()
  mark?: boolean;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

启动项目,用postman测试后发现并不好使,传了array类型的数据又要求是string类型,传了string类型的数据又要求是array类型。

注意:嵌套类型的对象验证需要使用@ValidateNested和@Type注解, @Type接受一个回调函数,函数内部需要返回一个用class声明的dto类。

解决方案

经过一番求助,翻了一圈class-validator的文档,发现没有现成的解决方案。那么,就只能自己拿到参数搞自定义校验了。

在class-transformer这个库中,提供了Transform方法,它接受一个回调函数作为参数,回调函数中提供了一个TransformFnParams类型的参数,其中的value字段就是客户端传过来的参数,我们只需要对其进行校验即可。

接下来,我们来看下实现代码,如下所示:

export class AppDto {
 @ApiProperty({ example: "2022年4月20日修改", description: "备注" })
  @IsOptional()
  @Transform(({ value }) => checkTitleKey(value))
  public text!: string | Array<TextObjType>;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

上述代码中,我们有一个名为checkTitleKey的校验函数,因为需要自己校验,所以就需要自己把TS的类型校验复刻一遍出来,实现代码如下所示:

  • 如果校验通过直接返回value参数即可
  • 如果校验不通过直接使用nest内置异常进行抛出即可
export function checkTitleKey(
  value: string | number | Array<TextObjType> | undefined | null
): any {
  if (typeof value === "string") {
    // 不做更改,直接返回
    return value;
  } else if (value instanceof Array) {
    // 不能为空数组
    if (value.length <= 0) {
      throw new BadRequestException(
        "property text cannot be an empty array",
        "Bad Request"
      );
    }
    for (let i = 0; i < value.length; i++) {
      // 校验数组中的对象字段
      const objKeys = Object.keys(value[i]);
      if (objKeys.length <= 0) {
        throw new BadRequestException(
          "property text contains empty objects",
          "Bad Request"
        );
      }
      // 必须包含content字段
      if (!objKeys.includes("content")) {
        throw new BadRequestException(
          "property text objects in the array must contain 'content'",
          "Bad Request"
        );
      }
      // 对每个key进行校验
      for (let j = 0; j < objKeys.length; j++) {
        switch (objKeys[j]) {
          case "content":
            // content字段必须为string类型
            if (typeof value[i].content !== "string") {
              throw new BadRequestException(
                "property text 'content' of the objects in the array must be of type string",
                "Bad Request"
              );
            }
            break;
          case "duration":
            if (typeof value[i].createTime !== "string") {
              throw new BadRequestException(
                "property text 'createTime' of the objects in the array must be of type number",
                "Bad Request"
              );
            }
            break;
          case "delay":
            if (typeof value[i].mark !== "boolean") {
              throw new BadRequestException(
                "property text 'mark' of the objects in the array must be of type number",
                "Bad Request"
              );
            }
            break;
          default:
            break;
        }
      }
    }
    return value;
  } else {
    throw new BadRequestException(
      "text must be an array or string",
      "Bad Request"
    );
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.

TextObjType的声明也需要进行相对应的修改,如下所示:

  • 全部变为可选参数,参数的必传与否已经在校验函数中处理了
  • 类型全部变为any
export type TextObjType = {
  content?: any;
  createTime?: any;
  mark?: any;
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

有一部分开发者可能比较迷惑,不是说ts用any是可耻行为吗,这我就要纠正下你了,既然它存在自然有使用场景。在我这个场景中,对象里所有key的类型校验都手动处理了,如果在此处定义了它的类型,在校验函数中就会报黄色警告,因此针对于需要手动校验类型的场景而言,使用any是最合适的。

结果校验

最后,我们针对于代码里定义的异常规则来验证下其是否能正常工作,如下所示:

# text字段为string类型
{
    "id":"122211",
    "title":"新的标题",
    "text":"新替换的文本内容",
    "name":"新的名字",
    "config":"var config = {\"name\":\"aa\",\"age\":\"21\",\"title\":\"标题测试\"}"
}
>>> 接口调用成功

# text字段为Array类型所有key都存在
{
    "id":"122211",
    "title":"新的标题",
    "text":[{"content":"新文本","createTime":"2022-04-20","mark":false}],
    "name":"新的名字",
    "config":"var config = {\"name\":\"aa\",\"age\":\"21\",\"title\":\"标题测试\"}"
}

>>> 接口调用成功

# text字段缺少content
{
    "id":"122211",
    "title":"新的标题",
    "text":[{"createTime":"2022-04-20","mark":false}],
    "name":"新的名字",
    "config":"var config = {\"name\":\"aa\",\"age\":\"21\",\"title\":\"标题测试\"}"
}
>>> 接口报错400:property text objects in the array must contain 'content'

# text字段为number类型
{
    "id":"122211",
    "title":"新的标题",
    "text":19,
    "name":"新的名字",
    "config":"var config = {\"name\":\"aa\",\"age\":\"21\",\"title\":\"标题测试\"}"
}
>>> 接口报错400:text must be an array or string

# text字段缺少createTime与mark
{
    "id":"122211",
    "title":"新的标题",
    "text":[{"content":"新文本"}],
    "name":"新的名字",
    "config":"var config = {\"name\":\"aa\",\"age\":\"21\",\"title\":\"标题测试\"}"
}
>>> 接口调用成功
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.

如下图所示,我们列举一个text字段为数字时的报错截图,运行结果符合预期,文章开头的问题成功解决: