rpc-client.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import Taro from '@tarojs/taro'
  2. import ResponsePolyfill from './response-polyfill'
  3. import { hc } from './hono-client/client'
  4. // API配置
  5. const API_BASE_URL = process.env.TARO_APP_API_BASE_URL || 'http://localhost:8080'
  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. console.log('response', response)
  37. const responseHeaders = response.header;
  38. // if (response.header) {
  39. // for (const [key, value] of Object.entries(response.header)) {
  40. // responseHeaders.set(key, value);
  41. // }
  42. // }
  43. // 处理204 No Content响应,不设置body
  44. const contentType = responseHeaders['content-type'] || responseHeaders['Content-Type'];
  45. const body = response.statusCode === 204
  46. ? null
  47. : (contentType && contentType.includes('application/json'))
  48. ? JSON.stringify(response.data)
  49. : response.data;
  50. return new ResponsePolyfill(
  51. body,
  52. {
  53. status: response.statusCode,
  54. statusText: response.errMsg || 'OK',
  55. headers: responseHeaders
  56. }
  57. )
  58. } catch (error) {
  59. console.error('API Error:', error)
  60. Taro.showToast({
  61. title: error.message || '网络错误',
  62. icon: 'none'
  63. })
  64. throw error
  65. }
  66. }
  67. // 创建Hono RPC客户端
  68. export const rpcClient = <T extends any>() => {
  69. // @ts-ignore
  70. return hc<T>(`${API_BASE_URL}`, {
  71. fetch: taroFetch
  72. })
  73. }