rpc-client.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import Taro from '@tarojs/taro'
  2. import { hc } from 'hono/client'
  3. import ResponsePolyfill from './response-polyfill'
  4. // API配置
  5. const API_BASE_URL = process.env.TARO_APP_API_BASE_URL || 'http://localhost:3000'
  6. // 完整的API地址
  7. // const BASE_URL = `${API_BASE_URL}/api/${API_VERSION}`
  8. // 创建自定义fetch函数,适配Taro.request
  9. const taroFetch: any = async (input, init) => {
  10. const url = typeof input === 'string' ? input : input.url
  11. const method = init.method || 'GET'
  12. const requestHeaders: Record<string, string> = init.headers;
  13. const keyOfContentType = Object.keys(requestHeaders).find(item => item.toLowerCase() === 'content-type')
  14. if (!keyOfContentType) {
  15. requestHeaders['content-type'] = 'application/json'
  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('mini_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. console.log('options', options)
  35. const response = await Taro.request(options)
  36. const responseHeaders = response.header;
  37. // if (response.header) {
  38. // for (const [key, value] of Object.entries(response.header)) {
  39. // responseHeaders.set(key, value);
  40. // }
  41. // }
  42. // 处理204 No Content响应,不设置body
  43. const body = response.statusCode === 204
  44. ? null
  45. : responseHeaders['content-type']!.includes('application/json')
  46. ? JSON.stringify(response.data)
  47. : response.data;
  48. return new ResponsePolyfill(
  49. body,
  50. {
  51. status: response.statusCode,
  52. statusText: response.errMsg || 'OK',
  53. headers: responseHeaders
  54. }
  55. )
  56. } catch (error) {
  57. console.error('API Error:', error)
  58. Taro.showToast({
  59. title: error.message || '网络错误',
  60. icon: 'none'
  61. })
  62. throw error
  63. }
  64. }
  65. // 创建Hono RPC客户端
  66. export const rpcClient = <T extends any>() => {
  67. // @ts-ignore
  68. return hc<T>(`${API_BASE_URL}`, {
  69. fetch: taroFetch
  70. })
  71. }