56 lines
1.9 KiB
Markdown
56 lines
1.9 KiB
Markdown
# request.ts
|
||
|
||
**路径**:`src/api/request.ts`
|
||
|
||
## 功能用途
|
||
|
||
HTTP 请求基础封装,提供 `get`、`post`、`put`、`buildQuery` 方法,以及 WebSocket URL 生成。所有 API 模块均通过此文件发起请求。
|
||
|
||
## 核心能力
|
||
|
||
- 统一 BASE_URL:默认 `https://api.xtrader.vip`,可通过环境变量 `VITE_API_BASE_URL` 覆盖
|
||
- **buildQuery**:过滤空值(undefined、''、[]、NaN)后构建 query 对象,供 GET 请求使用
|
||
- CLOB WebSocket URL:`getClobWsUrl()` 返回 `ws(s)://host/clob/ws`
|
||
- User WebSocket URL:`getUserWsUrl()` 返回 `ws(s)://host/clob/ws/user`(订单/持仓/余额推送)
|
||
- GET 请求:支持 query 参数,自动序列化
|
||
- POST 请求:支持 JSON body
|
||
- PUT 请求:支持 JSON body
|
||
- 自定义 headers:通过 `RequestConfig.headers` 传入
|
||
- **Accept-Language**:所有 GET/POST/PUT 请求自动附带当前 vue-i18n 的 `locale`
|
||
|
||
## 使用方式
|
||
|
||
```typescript
|
||
import { get, post, put, buildQuery, getClobWsUrl, getUserWsUrl } from '@/api/request'
|
||
|
||
// 构建 query(自动过滤空值)
|
||
const query = buildQuery({ page: 1, pageSize: 10, keyword, tagIds })
|
||
const data = await get<MyResponse>('/path', query)
|
||
|
||
// CLOB / User WebSocket URL
|
||
const clobWsUrl = getClobWsUrl()
|
||
const userWsUrl = getUserWsUrl()
|
||
|
||
// 带鉴权
|
||
const data = await get<MyResponse>('/path', undefined, {
|
||
headers: { 'x-token': token, 'x-user-id': userId },
|
||
})
|
||
|
||
// POST 请求
|
||
const res = await post<MyResponse>('/path', { key: 'value' }, {
|
||
headers: { 'x-token': token },
|
||
})
|
||
|
||
// PUT 请求
|
||
const putRes = await put<MyResponse>('/path', { key: 'value' }, {
|
||
headers: { 'x-token': token },
|
||
})
|
||
```
|
||
|
||
## 扩展方式
|
||
|
||
1. **添加 DELETE**:仿照 `get`/`post`/`put` 实现 `del` 函数
|
||
2. **统一错误处理**:在 `get`/`post` 内对 `!res.ok` 做统一 toast 或错误上报
|
||
3. **请求/响应拦截**:在 fetch 前后加入拦截逻辑(如 loading、日志)
|
||
4. **超时控制**:使用 `AbortController` 实现超时取消
|