| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- import Taro from '@tarojs/taro'
- import { hc } from 'hono/client'
- import type { AuthRoutes, UserRoutes, RoleRoutes, FileRoutes } from '@/server/api'
- // API配置
- const API_BASE_URL = process.env.TARO_APP_API_BASE_URL || 'http://localhost:3000'
- // 完整的API地址
- // const BASE_URL = `${API_BASE_URL}/api/${API_VERSION}`
- // 创建自定义fetch函数,适配Taro.request
- const taroFetch: typeof fetch = async (input, init) => {
- const url = typeof input === 'string' ? input : input.url
- const method = init?.method || 'GET'
-
- // 构建Taro请求选项
- const options: Taro.request.Option = {
- url,
- method: method as any,
- data: init?.body,
- header: {
- 'Content-Type': 'application/json',
- ...Object.fromEntries(new Headers(init?.headers || {}))
- }
- }
- // 添加token
- const token = Taro.getStorageSync('token')
- if (token) {
- options.header = {
- ...options.header,
- 'Authorization': `Bearer ${token}`
- }
- }
- try {
- const response = await Taro.request(options)
- const responseHeaders = new Headers();
- if (response.header) {
- for (const [key, value] of Object.entries(response.header)) {
- responseHeaders.set(key, value);
- }
- }
- // 处理204 No Content响应,不设置body
- const body = response.statusCode === 204
- ? null
- : responseHeaders.get('content-type')?.includes('application/json')
- ? JSON.stringify(response.data)
- : response.data;
- return new Response(
- body,
- {
- status: response.statusCode,
- statusText: response.errMsg || 'OK',
- headers: responseHeaders
- }
- )
- } catch (error) {
- console.error('API Error:', error)
- Taro.showToast({
- title: error.message || '网络错误',
- icon: 'none'
- })
- throw error
- }
- }
- // 创建Hono RPC客户端
- const createRpcClient = <T>(basePath: string) => {
- return hc<T>(`${API_BASE_URL}`, {
- fetch: taroFetch
- })
- }
- // 创建各个模块的RPC客户端
- export const authClient = createRpcClient<AuthRoutes>('/').api.v1.auth
- export const userClient = createRpcClient<UserRoutes>('/').api.v1.users
- export const roleClient = createRpcClient<RoleRoutes>('/').api.v1.roles
- export const fileClient = createRpcClient<FileRoutes>('/').api.v1.files
|