update
This commit is contained in:
82
.roo/rules/08-rpc.md
Normal file
82
.roo/rules/08-rpc.md
Normal file
@@ -0,0 +1,82 @@
|
||||
# RPC 调用规范
|
||||
|
||||
## 常见不规范问题
|
||||
1. **InferResponseType有[':id']时问题**:
|
||||
- ❌ InferResponseType<typeof zichanClient[':id'].$get, 200>
|
||||
- ✅ $get要加中括号 InferResponseType<typeof zichanClient[':id']['$get'], 200>
|
||||
|
||||
## 核心原则
|
||||
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<AuthRoutes>('/', {
|
||||
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<typeof client.method.$get, 200>['data'];
|
||||
```
|
||||
|
||||
- **请求类型提取**:
|
||||
- 使用 `InferRequestType` 从客户端方法提取请求类型
|
||||
- 必须指定正确的请求参数类型('json'|'form'|'param')
|
||||
- 示例:
|
||||
```typescript
|
||||
type RequestType = InferRequestType<typeof client.method.$post>['json'];
|
||||
```
|
||||
|
||||
- **类型命名规范**:
|
||||
- 响应类型: `[ResourceName]`
|
||||
- 请求类型: `[ResourceName]Post` 或 `[ResourceName]Put`
|
||||
- 示例:
|
||||
```typescript
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
type ZichanInfo = InferResponseType<typeof zichanClient.$get, 200>['data'][0];
|
||||
type ZichanListResponse = InferResponseType<typeof zichanClient.$get, 200>;
|
||||
type ZichanDetailResponse = InferResponseType<typeof zichanClient[':id']['$get'], 200>;
|
||||
type CreateZichanRequest = InferRequestType<typeof zichanClient.$post>['json'];
|
||||
type UpdateZichanRequest = InferRequestType<typeof zichanClient[':id']['$put']>['json'];
|
||||
type DeleteZichanResponse = InferResponseType<typeof zichanClient[':id']['$delete'], 200>;
|
||||
```
|
||||
Reference in New Issue
Block a user