2
0
Эх сурвалжийг харах

♻️ refactor(api): 重构API客户端代码结构

- 将mini项目中的API客户端逻辑从api.ts迁移到新文件rpc-client.ts
- 统一API客户端创建方式,使用rpcClient函数替代createRpcClient
- 优化客户端代码格式,修复缩进和空格问题
- 改进错误处理逻辑,增强代码可读性和可维护性
yourname 4 сар өмнө
parent
commit
c9b4c4d52d

+ 5 - 79
mini/src/utils/api.ts

@@ -1,82 +1,8 @@
-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
-  })
-}
+import { rpcClient } from './rpc-client'
 
 // 创建各个模块的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
+export const authClient = rpcClient<AuthRoutes>().api.v1.auth
+export const userClient = rpcClient<UserRoutes>().api.v1.users
+export const roleClient = rpcClient<RoleRoutes>().api.v1.roles
+export const fileClient = rpcClient<FileRoutes>().api.v1.files

+ 75 - 0
mini/src/utils/rpc-client.ts

@@ -0,0 +1,75 @@
+import Taro from '@tarojs/taro'
+import { hc } from 'hono/client'
+
+// 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客户端
+export const rpcClient = <T>() => {
+  return hc<T>(`${API_BASE_URL}`, {
+    fetch: taroFetch
+  })
+}

+ 15 - 15
src/client/api.ts

@@ -7,23 +7,23 @@ import type {
 
 // 创建 axios 适配器
 const axiosFetch = async (url: RequestInfo | URL, init?: RequestInit) => {
-  const requestHeaders:Record<string, string> = {};
-  
-  if(init?.headers instanceof Headers) {
+  const requestHeaders: Record<string, string> = {};
+
+  if (init?.headers instanceof Headers) {
     init.headers.forEach((value, key) => {
       requestHeaders[key] = value;
     })
   }
 
-  const response = await axios.request({  
-    url: url.toString(),  
-    method: init?.method || 'GET',  
-    headers: requestHeaders,  
-    data: init?.body,  
+  const response = await axios.request({
+    url: url.toString(),
+    method: init?.method || 'GET',
+    headers: requestHeaders,
+    data: init?.body,
   }).catch((error) => {
     console.log('axiosFetch error', error)
-    
-    if(isAxiosError(error)) {
+
+    if (isAxiosError(error)) {
       return {
         status: error.response?.status,
         statusText: error.response?.statusText,
@@ -32,7 +32,7 @@ const axiosFetch = async (url: RequestInfo | URL, init?: RequestInit) => {
       }
     }
     throw error;
-  }) 
+  })
 
   const responseHeaders = new Headers();
   if (response.headers) {
@@ -40,15 +40,15 @@ const axiosFetch = async (url: RequestInfo | URL, init?: RequestInit) => {
       responseHeaders.set(key, value);
     }
   }
-    
-  
+
+
   // 处理204 No Content响应,不设置body
   const body = response.status === 204
     ? null
     : responseHeaders.get('content-type')?.includes('application/json')
       ? JSON.stringify(response.data)
       : response.data;
-  
+
   return new Response(
     body,
     {
@@ -57,7 +57,7 @@ const axiosFetch = async (url: RequestInfo | URL, init?: RequestInit) => {
       headers: responseHeaders
     }
   )
-}  
+}
 
 
 export const authClient = hc<AuthRoutes>('/', {