05 API 与请求层
5.1 请求入口
app/plugins/http.ts 创建全局 $api:
ts
const $api = $fetch.create({
baseURL: config.public.apiBase || '/api',
timeout: config.public.apiTimeout || 10000,
})业务代码不应在页面中直接拼接底层请求细节,优先使用 app/infrastructure/http/clients/ 中的 Client。
5.2 API Client 分层
当前 Client 按业务域拆分,包括:
AuthApiClient:登录、用户信息和 Token 刷新。ItemApiClient:商品与商品详情。CartApiClient:购物车。OrderApiClient:订单。PaymentApiClient:支付。AftersalesApiClient:售后。AddressApiClient:收货地址。CouponApiClient、PointApiClient、CollectApiClient:优惠券、积分和收藏。StoreApiClient、TemplateApiClient:店铺和模板。CommonApiClient、UploadApiClient:公共接口和文件上传。
统一从 app/infrastructure/http/index.ts 或 clients 的 index.ts 导出。
5.3 请求参数注入
请求插件会统一处理:
Authorization: Bearer <token>。company_id:由公司配置解析。country_code:由当前语言映射。- POST/PUT/PATCH 默认转换为
application/x-www-form-urlencoded。 FormData保留 multipart boundary,并补充全局参数。useJson: true可跳过默认表单编码。skipAuth、skipCompanyId、skipCountryCode可用于特殊接口。
GET 或无 body 请求将全局参数放入 query;有 body 的普通请求将其放入 body。
5.4 响应与错误
成功响应会自动解包 data。如果业务响应包含 status_code >= 400,插件会创建 BUSINESS_ERROR 并根据配置显示提示。
HTTP 错误按状态码归类:
401:认证错误,客户端跳转登录页。403:权限错误。422:参数校验错误。500+:服务端错误。- 无响应:网络、超时或未知错误。
408、429、500、502、503、504 默认可重试,ofetch 自动重试 3 次,间隔 1 秒。特殊调用可通过 skipErrorCodes 避免全局 Toast。
5.5 新增 API Client
- 在
clients/新建按领域命名的 Client。 - 定义请求和响应类型,避免使用无约束的
any。 - 在 Client 内调用
$api,不要重复创建 fetch 实例。 - 需要领域模型时增加 Transformer。
- 从
clients/index.ts导出并补充测试。
