@anatine/zod-openapi (英语)
转换 a 佐德语Name openAPI 计划 SchemaObject 定义 打开api3-ts
安装
Openapi3-ts和zod都是同级依赖性而不是依赖性包.
虽然 zod 操作所必需的, openapi3-ts 用于类型广播.
npm install openapi3-ts zod @anatine/zod-openapi
使用量
选择任何 Zod 方案并将其转换为 OpenAPI JSON 对象
import { generateSchema } from '@anatine/zod-openapi';
const aZodSchema = z.object({
uid: z.string().nonempty(),
firstName: z.string().min(2),
lastName: z.string().optional(),
email: z.string().email(),
phoneNumber: z.string().min(10).optional(),
})
const myOpenApiSchema = generateSchema(aZodSchema);
// ...
这将生成 OpenAPI 方案 myOpenApiSchema
{
"type": "object",
"properties": {
"uid": {
"type": "string",
"minLength": 1
},
"firstName": {
"type": "string",
"minLength": 2
},
"lastName": {
"type": "string"
},
"email": {
"type": "string",
"format": "email"
},
"phoneNumber": {
"type": "string",
"minLength": 10
}
},
"required": [
"uid",
"firstName",
"email"
]
}
通过函数包装器将 Zod 方案扩展为额外的 OpenAPI 方案
import { extendApi, generateSchema } from '@anatine/zod-openapi';
const aZodExtendedSchema = extendApi(
z.object({
uid: extendApi(z.string().nonempty(), {
title: 'Unique ID',
description: 'A UUID generated by the server',
}),
firstName: z.string().min(2),
lastName: z.string().optional(),
email: z.string().email(),
phoneNumber: extendApi(z.string().min(10), {
description: 'US Phone numbers only',
example: '555-555-5555',
}),
}),
{
title: 'User',
description: 'A user schema',
}
);
const myOpenApiSchema = generateSchema(aZodExtendedSchema);
// ...
...或通过Zod计划扩展:
import { extendApi, generateSchema, extendZodWithOpenApi } from '@anatine/zod-openapi';
import {z} from 'zod';
extendZodWithOpenApi(z);
const aZodExtendedSchema =
z.object({
uid: z.string().nonempty().openapi({
title: 'Unique ID',
description: 'A UUID generated by the server',
}),
firstName: z.string().min(2),
lastName: z.string().optional(),
email: z.string().email(),
phoneNumber: z.string().min(10).openapi({
description: 'US Phone numbers only',
example: '555-555-5555',
}),
}).openapi(
{
title: 'User',
description: 'A user schema',
}
);
const myOpenApiSchema = generateSchema(aZodExtendedSchema);
// ...
这将产生一个扩展的策略:
{
"type": "object",
"properties": {
"uid": {
"type": "string",
"minLength": 1,
"title": "Unique ID",
"description": "A UUID generated by the server"
},
"firstName": {
"type": "string",
"minLength": 2
},
"lastName": {
"type": "string"
},
"email": {
"type": "string",
"format": "email"
},
"phoneNumber": {
"type": "string",
"minLength": 10,
"description": "US Phone numbers only",
"example": "555-555-5555"
}
},
"required": [
"uid",
"firstName",
"email",
"phoneNumber"
],
"title": "User",
"description": "A user schema"
}
贷项
-
快速分区- api
一个伟大的自由, 提供了一些洞察 处理各种zod类型.
-
zod-dto 读取
Lib 提供与 NestJS 一起使用 Zod 的见解
这个库是 nx 单列波的一部分 @anatine/zod-plugins (韩语)。 。 。 .