rpc-client.ts 1.9 KB

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