rpc-client.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import Taro from '@tarojs/taro'
  2. import { hc } from 'hono/client'
  3. // API配置
  4. const API_BASE_URL = process.env.TARO_APP_API_BASE_URL || 'http://localhost:3000'
  5. // 完整的API地址
  6. // const BASE_URL = `${API_BASE_URL}/api/${API_VERSION}`
  7. // 创建自定义fetch函数,适配Taro.request
  8. const taroFetch: typeof fetch = async (input, init) => {
  9. const url = typeof input === 'string' ? input : input.url
  10. const method = init.method || 'GET'
  11. const requestHeaders: Record<string, string> = {};
  12. if (init.headers instanceof Headers) {
  13. init.headers.forEach((value, key) => {
  14. requestHeaders[key] = value;
  15. })
  16. }
  17. // 构建Taro请求选项
  18. const options: Taro.request.Option = {
  19. url,
  20. method: method as any,
  21. data: init.body,
  22. header: requestHeaders
  23. }
  24. // 添加token
  25. const token = Taro.getStorageSync('token')
  26. if (token) {
  27. options.header = {
  28. ...options.header,
  29. 'Authorization': `Bearer ${token}`
  30. }
  31. }
  32. try {
  33. const response = await Taro.request(options)
  34. const responseHeaders = new Headers();
  35. if (response.header) {
  36. for (const [key, value] of Object.entries(response.header)) {
  37. responseHeaders.set(key, value);
  38. }
  39. }
  40. // 处理204 No Content响应,不设置body
  41. const body = response.statusCode === 204
  42. ? null
  43. : responseHeaders.get('content-type')!.includes('application/json')
  44. ? JSON.stringify(response.data)
  45. : response.data;
  46. return new Response(
  47. body,
  48. {
  49. status: response.statusCode,
  50. statusText: response.errMsg || 'OK',
  51. headers: responseHeaders
  52. }
  53. )
  54. } catch (error) {
  55. console.error('API Error:', error)
  56. Taro.showToast({
  57. title: error.message || '网络错误',
  58. icon: 'none'
  59. })
  60. throw error
  61. }
  62. }
  63. // 创建Hono RPC客户端
  64. export const rpcClient = <T>() => {
  65. return hc<T>(`${API_BASE_URL}`, {
  66. fetch: taroFetch
  67. })
  68. }