TypeScript到JSON Schema生成器:ts-json-schema-generator

TypeScript到JSON Schema生成器:ts-json-schema-generator

ts-json-schema-generatorGenerate JSON schema from your Typescript sources项目地址:https://gitcode.com/gh_mirrors/ts/ts-json-schema-generator

1. 项目介绍

ts-json-schema-generator 是一个用于从TypeScript源代码自动生成JSON Schema的工具。这个项目由Vega维护,它的主要目标是帮助开发者将他们的类型定义转化为可验证的数据模式,以便在API交互或者客户端数据校验中使用。

该库支持自定义配置,包括指定源文件路径、选择特定类型生成JSON Schema,以及自定义$Id和JsDoc注解的处理方式等。此外,它还提供了一个命令行接口(CLI)方便快速生成JSON Schema。

2. 项目快速启动

安装

通过npm安装ts-json-schema-generator:

npm install --save ts-json-schema-generator

命令行使用

生成JSON Schema:

npx ts-json-schema-generator \
  --path 'my/project/**/*.ts' \ 
  --type 'MyTypeName'

或在本地环境中运行:

./node_modules/.bin/ts-json-schema-generator \
  --path 'my/project/**/*.ts' \ 
  --type 'MyTypeName'

程序化使用

在你的Node.js应用程序中,你可以这样使用:

const tsj = require('ts-json-schema-generator');
const fs = require('fs');

// 配置项
const config = {
  path: 'path/to/source/file',
  tsconfig: 'path/to/tsconfig.json', // 可选
  type: 'MyTypeName', // 或者指定要生成的单个类型名
};

const outputPath = 'path/to/output/file';
const schemaGen = tsj.createGenerator(config);
const schema = schemaGen.createSchema(config.type);

const schemaStr = JSON.stringify(schema, null, 2);
fs.writeFile(outputPath, schemaStr, (err) => {
  if (err) throw err;
});

3. 应用案例和最佳实践

  • API校验: 将生成的JSON Schema应用于服务器端,校验客户端发送的请求数据。
  • 客户端数据绑定: 在前端框架中,如Angular或React,利用JSON Schema进行表单验证和自动模型绑定。
  • 数据交换规范: 定义微服务间的数据交换格式,确保正确性。

最佳实践:

  1. 使用TypeScript的类型注解来定义清晰的数据结构。
  2. 当需要生成多个类型的schema时,分别调用createSchema()方法。
  3. 根据项目需求调整配置,例如设置自定义$id,以符合你的命名规范。

4. 典型生态项目

  • typescript-json-schema: 另一个流行的JSON Schema生成库,可以作为替代方案。
  • ajv: 一个高效的JSON Schema验证库,与ts-json-schema-generator配合使用进行数据校验。
  • json-editor: 一个基于JSON Schema的JSON编辑器,可以在浏览器端展示并编辑数据。

以上就是ts-json-schema-generator的基本介绍及使用指南。借助此项目,您可以轻松地将TypeScript类型转换成强大的JSON Schema规范,提升数据一致性并简化开发流程。

ts-json-schema-generatorGenerate JSON schema from your Typescript sources项目地址:https://gitcode.com/gh_mirrors/ts/ts-json-schema-generator

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乌想炳Todd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值