NEST.JS验证:字符串[] |字符串(联合类型)

发布于 2025-02-11 06:15:26 字数 457 浏览 3 评论 0原文

我有两个API,一个有REST客户端,向另一个提出请求,我想验证其收到的API错误。

API错误签名为(在打字稿中):

class ApiError {
  error?: string;
  message: string | string[];
  statusCode: number;
}

现在我验证的问题是消息,它是字符串的字符串类型和字符串数组。我想知道是否有某种方法可以使用@nestjs/class-validator库来验证它。像:

class ExternalApiErrorDto {
  @IsString()
  @IsOptional()
  error?: string;
  message: string | string[];
  @IsPositive()
  statusCode: number;
}

I have two APIs, one has rest client that makes requests to the other and I would like to validate the api error it receives.

The api error signature is (in typescript):

class ApiError {
  error?: string;
  message: string | string[];
  statusCode: number;
}

Now what I have trouble validating is the message, it is a union type of string and array of string. I want to know if there is some way to validate it using the @nestjs/class-validator library. Something like:

class ExternalApiErrorDto {
  @IsString()
  @IsOptional()
  error?: string;
  message: string | string[];
  @IsPositive()
  statusCode: number;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巡山小妖精 2025-02-18 06:15:26

我最终将预期的消息转换为一个数组,并通过执行以下操作来验证这是一系列字符串:

export class ExternalApiErrorDto {
  @IsString()
  @IsOptional()
  error?: string;
  @Transform(({ value }) => (Array.isArray(value) ? value : [value]))
  @IsString({ each: true })
  message: string[];
  @IsPositive()
  statusCode: number;
}

无论哪种方式,都很高兴知道如何验证联合类型。一种可能性可能是使用自定义验证器,实施
验证器constraintInterface

I end up transforming the expected message into an array and validating if it's an array of strings by doing the following:

export class ExternalApiErrorDto {
  @IsString()
  @IsOptional()
  error?: string;
  @Transform(({ value }) => (Array.isArray(value) ? value : [value]))
  @IsString({ each: true })
  message: string[];
  @IsPositive()
  statusCode: number;
}

Either way, it would be great to know how to validate a union type. One possibility could perhaps be to use a custom validator, implementing
ValidatorConstraintInterface.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文