# RPC 调用规范 ## 常见不规范问题 1. **InferResponseType有[':id']时问题**: - ❌ InferResponseType - ✅ $get要加中括号 InferResponseType ## 核心原则 1. **类型安全**: - 所有RPC调用必须基于OpenAPI定义的类型 - 客户端和服务端类型必须严格匹配 2. **一致性**: - RPC调用路径必须与OpenAPI路由定义一致 - 错误处理格式必须统一 3. **api版本**: - 所有RPC调用必须基于OpenAPI定义的版本 - 版本号必须与OpenAPI版本号一致 目前仅支持v1版本 示例: ```typescript import { authClient } from '@/client/api'; ``` ## 客户端规范 ### 1. 客户端初始化 ```typescript import { hc } from 'hono/client' import { AuthRoutes } from '@/server/api'; export const authClient = hc('/', { fetch: axiosFetch, }).api.v1.auth; ``` ### 2. 方法调用 - 必须使用解构方式组织RPC方法 - 方法命名必须与OpenAPI路由定义一致 - 示例: ```typescript const res = await authClient.templates.blank[':templateType'].$get({ param: { templateType } }); if (res.status !== 200) { throw new Error(res.message); } const templateInfo = await res.json(); ``` ### 3. 类型提取规范 - **响应类型提取**: - 使用 `InferResponseType` 从客户端方法提取响应类型 - 必须指定正确的响应状态码(通常为200) - 示例: ```typescript type ResponseType = InferResponseType['data']; ``` - **请求类型提取**: - 使用 `InferRequestType` 从客户端方法提取请求类型 - 必须指定正确的请求参数类型('json'|'form'|'param') - 示例: ```typescript type RequestType = InferRequestType['json']; ``` - **类型命名规范**: - 响应类型: `[ResourceName]` - 请求类型: `[ResourceName]Post` 或 `[ResourceName]Put` - 示例: ```typescript import type { InferRequestType, InferResponseType } from 'hono/client' type ZichanInfo = InferResponseType['data'][0]; type ZichanListResponse = InferResponseType; type ZichanDetailResponse = InferResponseType; type CreateZichanRequest = InferRequestType['json']; type UpdateZichanRequest = InferRequestType['json']; type DeleteZichanResponse = InferResponseType; ```