| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- 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'
- const API_VERSION = process.env.TARO_APP_API_VERSION || 'v1'
- // 完整的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)
-
- // 处理401未授权
- if (response.statusCode === 401) {
- Taro.removeStorageSync('token')
- Taro.removeStorageSync('userInfo')
- Taro.navigateTo({ url: '/pages/login/index' })
- throw new Error('请重新登录')
- }
- // 适配fetch响应格式
- return {
- ok: response.statusCode >= 200 && response.statusCode < 300,
- status: response.statusCode,
- statusText: response.errMsg || 'OK',
- headers: new Headers(response.header || {}),
- url: response.data?.url || url,
- json: async () => response.data,
- text: async () => JSON.stringify(response.data),
- blob: async () => new Blob([JSON.stringify(response.data)]),
- arrayBuffer: async () => new TextEncoder().encode(JSON.stringify(response.data)),
- clone: () => ({}) as Response,
- body: null as any,
- bodyUsed: true
- } as Response
- } 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>(`${BASE_URL}${basePath}`, {
- fetch: taroFetch
- })
- }
- // 创建各个模块的RPC客户端
- export const authClient = createRpcClient<AuthRoutes>('/auth')
- export const userClient = createRpcClient<UserRoutes>('/users')
- export const roleClient = createRpcClient<RoleRoutes>('/roles')
- export const fileClient = createRpcClient<FileRoutes>('/files')
- // 类型定义
- export type {
- AuthRoutes,
- UserRoutes,
- RoleRoutes,
- FileRoutes
- }
- // 默认导出RPC客户端
- export default {
- auth: authClient,
- users: userClient,
- roles: roleClient,
- files: fileClient,
- }
|