跳至正文
Wener Notes

zod

约 2 分钟阅读
    • adpoted by:
  • 参考
TypeScript
// 校验合法 JSON 对象
const LiteralSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
type Literal = z.infer<typeof LiteralSchema>;
type Json = Literal | { [key: string]: Json } | Json[];
const JsonSchema: z.ZodType<Json> = z.lazy(() => z.union([LiteralSchema, z.array(JsonSchema), z.record(JsonSchema)]));

openapi

TypeScript
import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';
import { z } from 'zod';

// 增加 openapi 方法
extendZodWithOpenApi(z);

// 支持定义额外数据
z.string().openapi({ description: 'Some string' });
  • 使用 registry 定义接口方法
  • 通过 schema 定义的对象默认会包含在 registry 中
TypeScript
import { OpenAPIRegistry, OpenApiGeneratorV3 } from '@asteasolutions/zod-to-openapi';

const registry = new OpenAPIRegistry();

// Registry 也可以定义 Schema
const UserSchema = registry.register(
  'User',
  z.object({
    id: z.string().openapi({ example: '1212121' }),
    name: z.string().openapi({ example: 'John Doe' }),
    age: z.number().openapi({ example: 42 }),
  }),
);

// 定义接口
registry.registerPath({
  method: 'get',
  path: '/users/{id}',
  description: 'Get user data by its id',
  summary: 'Get a single user',
  request: {
    params: z.object({
      id: z.string().openapi({ example: '1212121' }),
    }),
  },
  responses: {
    200: {
      description: 'Object with user data.',
      content: {
        'application/json': {
          schema: UserSchema,
        },
      },
    },
    204: {
      description: 'No content - successful operation',
    },
  },
});

const generator = new OpenApiGeneratorV3(registry.definitions);

// 生成文档
generator.generateComponents();

Version

  • v4.5
    • z.compile
      • import "zod/compile"; 在定义 schema 之前 import 自动默认都走 compile
    • z.properties
    • z.deepPartial
    • z.validate()
    • zod.dev/blog/zod-4-5
  • v4
    • 拆分 core, mini, 完整
    • 支持直接生成 jsonschema

关联信息

反向链接、本文链接的其他页面和外部资料。

反向链接

  • JavaScript Awesome
    笔记 · zod

    novnc/noVNC · felixrieseberg/macintosh.js · RobinCsl/awesome-js-tooling-not-in-js · sorrycc/awesome-javascript · CLI / Table

站内链接

  • trpc
    笔记 · tRPC

    trpc/trpc · @trpc/next - NextJS · spec · https://trpc.io/docs/rpc · 参考 · jlalmes/trpc-openapi · 使用 meta 定义路由 · - · 使用 zod 定义 input 和 output

参考资料

GitHub9 条
其他外链2 条
最近更新commit 537865f编辑