Schema Studio · @trasm/thrift-jsma
Thrift 转 JSON Schema:转换、递归与校验
Schema Studio 把 Apache Thrift 的 struct 转成 JSON Schema,并允许用样例 JSON 校验字段。只需试一次转换就用在线编辑器;需要在脚本或 CI 中重复生成时,用 TypeScript SDK。
在线转换:必填与可选字段
把下面的 Thrift IDL 粘贴到左侧编辑器,右侧会显示 JSON Schema。
struct User {
1: required string name
2: optional string email
}
输出节选:只有 name 会出现在 required 数组中。
{
"type": "object",
"properties": {
"name": { "type": "string" },
"email": { "type": "string" }
},
"required": ["name"]
}
转换递归结构:列表中的 $ref
在演练场选择「递归引用」。列表的 items.$ref 指回当前结构的 $id,而不是把结构无限展开。嵌套层的 type 仍然必须是字符串。
以下 SDK 示例基于仓库当前源码。npm 的 0.0.5 使用的是旧构建:不要把它与本页的递归和 TypeBox 1 示例混用。
用 Node.js 24.22.2 和 pnpm 12.21.0 在仓库根目录执行以下命令。进入演练场目录后,把任一示例保存为 example.mjs,再运行 node example.mjs。
pnpm install --frozen-lockfile
pnpm build
cd app/parser-view
import { parseThriftToJsonSchema } from '@trasm/thrift-jsma'
const idl = `
struct FlexFilter {
1: required string type
2: optional list<FlexFilter> sub_conditions
}
`
const schema = JSON.parse(parseThriftToJsonSchema(idl))
const child = schema.properties.sub_conditions.items
console.log(child.$ref === schema.$id) // true
使用 TypeBox 1 校验 JSON
parseThriftToJsonSchema() 返回 JSON 文本;parseThriftToTypeBox() 返回可交给 TypeBox 的 schema 对象。
import { parseThriftToTypeBox } from '@trasm/thrift-jsma'
import { Compile } from 'typebox/compile'
const idl = 'struct User { 1: required string name }'
const schema = parseThriftToTypeBox(idl)
if (!schema) throw new Error('No schema generated')
const validator = Compile(schema)
console.log(validator.Check({ name: 'Ada' })) // true
console.log(validator.Check({ name: 7 })) // false