feat: update adapter to use globalThis for origin resolution fix: remove unused ClientQuery export from query.ts chore: update tsconfig to include test files and set rootDir feat: add create-query functionality for dynamic API generation feat: implement QueryApi with enhanced type inference from JSON Schema test: add comprehensive API tests for QueryApi functionality test: create demo routes and schemas for testing purposes docs: add type inference demo for QueryApi usage
43 lines
1.2 KiB
TypeScript
43 lines
1.2 KiB
TypeScript
import z, { toJSONSchema } from "zod";
|
|
|
|
const schema = z.object({
|
|
name: z.string().describe("The name of the person"),
|
|
age: z.number().int().min(0).describe("The age of the person"),
|
|
email: z.string().optional().describe("The email address of the person"),
|
|
});
|
|
|
|
console.log("JSON Schema for the person object:");
|
|
console.log(
|
|
JSON.stringify(toJSONSchema(schema), null, 2)
|
|
);
|
|
const jsonSchema = toJSONSchema(schema);
|
|
|
|
const schema2 = z.fromJSONSchema(jsonSchema);
|
|
|
|
// schema2 的类型是 ZodSchema<any>,所以无法在编译时推断出具体类型
|
|
// 这是 fromJSONSchema 的限制 - JSON Schema 转换会丢失 TypeScript 类型信息
|
|
|
|
schema2.parse({
|
|
name: "John Doe",
|
|
age: 30, // 添加必需的 age 字段
|
|
email: "",
|
|
})
|
|
|
|
type Schema2Type = z.infer<typeof schema2>;
|
|
// Schema2Type 被推断为 any
|
|
|
|
// 对比:原始 schema 的类型推断是正常的
|
|
type OriginalSchemaType = z.infer<typeof schema>;
|
|
// OriginalSchemaType = { name: string; age: number; email?: string | undefined }
|
|
|
|
const v: Schema2Type = {
|
|
name: "John Doe",
|
|
email: ""
|
|
}
|
|
|
|
// 如果使用原始 schema,类型推断会正常工作:
|
|
const v2: OriginalSchemaType = {
|
|
name: "John Doe",
|
|
age: 30,
|
|
// email 是可选的
|
|
} |