更新依赖项版本,添加 Zod schema 示例

This commit is contained in:
2026-01-27 20:45:19 +08:00
parent d7354fdf49
commit a309180b2b
4 changed files with 51 additions and 9 deletions

View File

@@ -9,9 +9,10 @@
"keywords": [],
"author": "abearxiong <xiongxiao@xiongxiao.me> (https://www.xiongxiao.me)",
"license": "MIT",
"packageManager": "pnpm@10.14.0",
"packageManager": "pnpm@10.28.2",
"type": "module",
"dependencies": {
"zod": "^4.3.5"
"zod": "^4.3.6",
"zod-to-json-schema": "^3.25.1"
}
}

22
pnpm-lock.yaml generated
View File

@@ -9,14 +9,26 @@ importers:
.:
dependencies:
zod:
specifier: ^4.3.5
version: 4.3.5
specifier: ^4.3.6
version: 4.3.6
zod-to-json-schema:
specifier: ^3.25.1
version: 3.25.1(zod@4.3.6)
packages:
zod@4.3.5:
resolution: {integrity: sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==}
zod-to-json-schema@3.25.1:
resolution: {integrity: sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==}
peerDependencies:
zod: ^3.25 || ^4
zod@4.3.6:
resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}
snapshots:
zod@4.3.5: {}
zod-to-json-schema@3.25.1(zod@4.3.6):
dependencies:
zod: 4.3.6
zod@4.3.6: {}

View File

@@ -1,7 +1,10 @@
import { z } from 'zod'
import { z, parse } from 'zod'
const name = z.string().optional().describe('The name of the user')
// name.optional()
// console.log(name.description) // Output: The name of the user
const str = JSON.stringify(name)
console.log(JSON.stringify(name), name.description) // Output: The name of the user
// const nameClone =

26
src/schema.ts Normal file
View File

@@ -0,0 +1,26 @@
import { z, toJSONSchema, fromJSONSchema } from 'zod'
// 定义一个复杂的 Zod schema
const UserSchema = z.object({
name: z.string().optional().describe('用户名'),
age: z.number().min(0).max(150).describe('年龄'),
email: z.email().describe('邮箱'),
tags: z.array(z.string()).describe('标签列表'),
isActive: z.boolean().default(false).describe('是否激活')
}).describe('用户信息')
console.log('原始 Zod schema:', UserSchema.description)
// 示例
const serialized = toJSONSchema(UserSchema)
console.log('序列化后的 JSON Schema:')
console.log(serialized)
// 网络传输模拟
const transmitted = serialized
// 接收端反序列化
const restoredSchema = fromJSONSchema(transmitted)
console.log('\n反序列化后的 schema 类型:', typeof restoredSchema)
console.log(restoredSchema.description) // trueF