Nestjs验证管带有打字稿联合/交叉对象

发布于 2025-01-24 20:40:14 字数 1069 浏览 4 评论 0 原文

假设我们有以下键法类型:

type Parent = { mode: "A", a: string } | { mode: "B", b1: string, b2: Parent } | { mode : "C", c1: number, c2: Parent }
type Child = Parent & { x: string, y: number }

通过IO-ts htttps,它很容易为这些类型构造验证示意图 。 ://github.com/gcanti/io-ts npm-package,但不支持与inestjs集成,

因此似乎有必要使用AJV验证。 NESTJS通过此NPM-Package

有一个名为JSonschematype的好工具,可为耦合打字类型类型和相关的AJV架构提供机制。但似乎AJV验证器不支持嵌套的工会和交集 https://github.com /ajv-validator/ajv/eskoes/1302

因此,似乎有必要编写导致代码重复的独立模式和打字稿声明。好的。但是AJV本身并不能为工会提供良好的功能,而是强迫将所有可能的联合组合分配到一个顶级的单个Oneof定义中,

所以问题 - 是否存在与Nestjs兼容的功能强大的打字稿验证库?目标是以任何非冗余方式在代码中声明对象架构,并自动获得打字条类型和适当的运行时录音机。

所有这些功能在IO-TS中都支持,但它不适用于Nestjs验证管道:(

Suppose we have following Typescript types:

type Parent = { mode: "A", a: string } | { mode: "B", b1: string, b2: Parent } | { mode : "C", c1: number, c2: Parent }
type Child = Parent & { x: string, y: number }

It's very easy to construct validation schemata for these types by means of io-ts https://github.com/gcanti/io-ts npm-package, but integration with NestJS for io-ts is not supported

So it's seems that it's necessary to use AJV validation. Nestjs provides capability of validation piping using AJV via associated json-schema by means of this npm-package https://www.npmjs.com/package/nestjs-ajv-glue

There is good tool named JSONSchemaType which provides mechanism for coupling Typescript type and associated AJV schema. But also seems that AJV validator does not support nested unions and intersections https://github.com/ajv-validator/ajv/issues/1302

So it's seems that it's necessary to write independent schemas and Typescript declarations which causes code duplication. Ok. But AJV itself does not provide good capabilities for unions, forcing distribute all possible union combinations into one top-level oneOf definition

So question - are there powerful Typescript-aware validation libraries compatible with NestJS? Goal is declare object schema ONE TIME in code in any non-redundant way and get automatically underlying Typescript type and appropriate runtime-validator.

All these features are supported in io-ts, but it does not work with NestJS validation pipes :(

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文