NEST.JS验证:字符串[] |字符串(联合类型)
我有两个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最终将预期的消息转换为一个数组,并通过执行以下操作来验证这是一系列字符串:
无论哪种方式,都很高兴知道如何验证联合类型。一种可能性可能是使用自定义验证器,实施
验证器constraintInterface
。I end up transforming the expected message into an array and validating if it's an array of strings by doing the following:
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
.