tschema实战教程:5个高效构建API数据验证的完整示例 tschema实战教程5个高效构建API数据验证的完整示例【免费下载链接】tschemaA tiny (500b) utility to build JSON schema types.项目地址: https://gitcode.com/gh_mirrors/ts/tschematschema是一个轻量级仅500字节的工具用于构建JSON schema类型帮助开发者快速实现API数据验证。本文将通过5个实用示例展示如何使用tschema轻松处理各种常见的数据验证场景让你的API开发更高效、更可靠。1. 基础类型验证构建用户注册表单验证最常见的API验证场景是用户输入验证。使用tschema可以轻松定义字符串、数字等基础类型的验证规则import * as t from ./mod.ts; // 定义用户注册表单验证规则 const userSchema t.object({ username: t.string({ minLength: 3, maxLength: 20, description: 用户名必须为3-20个字符 }), email: t.string({ format: email, description: 请输入有效的邮箱地址 }), age: t.optional(t.integer({ minimum: 18, description: 年龄必须大于等于18岁 })), isActive: t.boolean({ default: true }) }); // 推断TypeScript类型 type User t.Infertypeof userSchema;这个示例展示了如何使用t.string()、t.integer()和t.boolean()等基础类型构造器以及如何添加验证规则如minLength、format和minimum。t.optional()修饰符可以将字段标记为可选。2. 复杂对象验证创建产品信息验证器对于包含嵌套结构的复杂对象tschema提供了强大的组合能力// 定义地址子 schema const addressSchema t.object({ street: t.string(), city: t.string(), zipCode: t.string({ pattern: ^\\d{5}$, description: 邮编必须是5位数字 }), country: t.constant(CN, { description: 目前仅支持中国地址 }) }); // 定义产品 schema const productSchema t.object({ id: t.string({ format: uuid }), name: t.string({ minLength: 1, maxLength: 100 }), price: t.number({ minimum: 0, exclusiveMinimum: true, description: 价格必须大于0 }), categories: t.array( t.enum([electronics, clothing, books]), { minItems: 1, description: 至少选择一个分类 } ), shippingAddress: t.optional(addressSchema) }); type Product t.Infertypeof productSchema;在这个示例中我们创建了一个嵌套的产品信息验证器展示了如何使用t.array()定义数组类型t.enum()定义枚举值以及如何嵌套使用t.object()来构建复杂对象结构。3. 高级组合验证实现订单状态流转验证tschema提供了anyOf、oneOf和allOf等组合器用于处理复杂的验证逻辑// 定义订单状态变更 schema const orderStatusSchema t.object({ orderId: t.string({ format: uuid }), status: t.one( t.constant(pending), t.constant(processing), t.constant(shipped), t.constant(delivered), t.constant(cancelled) ), // 根据状态不同需要提供不同的附加信息 details: t.any( t.object({ status: t.constant(cancelled), reason: t.string({ minLength: 5 }) }), t.object({ status: t.constant(shipped), trackingNumber: t.string() }), t.object({ status: t.any(t.constant(pending), t.constant(processing), t.constant(delivered)) }) ) }); type OrderStatus t.Infertypeof orderStatusSchema;这个示例使用t.one()确保状态只能是预定义的值之一并使用t.any()根据不同状态要求不同的附加信息实现了条件验证逻辑。4. 元组与字典验证处理灵活数据结构除了常规对象tschema还支持元组和字典等特殊数据结构// 元组示例表示经纬度坐标 const coordinateSchema t.tuple([ t.number({ minimum: -180, maximum: 180 }), // 经度 t.number({ minimum: -90, maximum: 90 }) // 纬度 ], { description: 经纬度坐标格式为 [longitude, latitude] }); // 字典示例表示用户权限映射 const permissionsSchema t.dict( t.boolean(), { description: 用户权限字典key为权限名称value为是否拥有该权限 } ); // 使用示例 const dataSchema t.object({ location: coordinateSchema, userPermissions: permissionsSchema }); type Data t.Infertypeof dataSchema;t.tuple()用于定义固定长度和类型的数组t.dict()则用于定义键类型灵活但值类型固定的字典结构这在处理地理位置数据、权限映射等场景非常有用。5. 只读与部分验证构建不可变数据模型tschema提供了readonly和partial等修饰符帮助构建不可变数据模型// 定义基础用户 schema const baseUserSchema t.object({ id: t.string({ format: uuid }), username: t.string(), email: t.string({ format: email }), role: t.enum([user, moderator, admin]) }); // 创建只读版本 const readonlyUserSchema t.readonly(baseUserSchema); // 创建部分更新版本所有字段可选 const updateUserSchema t.partial(baseUserSchema); // 使用示例获取用户只读 type ReadonlyUser t.Infertypeof readonlyUserSchema; // 使用示例更新用户部分字段 type UpdateUser t.Infertypeof updateUserSchema;t.readonly()确保数据不可修改t.partial()则将所有字段转为可选非常适合创建数据查询和更新的不同验证规则。快速开始使用tschema要开始使用tschema进行API数据验证只需按照以下步骤操作克隆仓库git clone https://gitcode.com/gh_mirrors/ts/tschema在项目中导入tschemaimport * as t from ./mod.ts;根据本文示例创建你的验证规则然后使用t.Infer获取TypeScript类型tschema的核心代码在mod.ts中包含了所有类型构造器和修饰符。测试用例mod.test.ts提供了更多使用示例你可以参考这些示例来深入学习tschema的各种功能。无论你是构建REST API、GraphQL服务还是任何需要数据验证的应用tschema都能帮助你以简洁的方式实现强大的类型验证同时获得TypeScript的类型支持。【免费下载链接】tschemaA tiny (500b) utility to build JSON schema types.项目地址: https://gitcode.com/gh_mirrors/ts/tschema创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考