hc.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import axios, { isAxiosError } from 'axios';
  2. import { hc } from 'hono/client'
  3. // 创建 axios 适配器
  4. const axiosFetch = async (url: RequestInfo | URL, init?: RequestInit) => {
  5. const requestHeaders: Record<string, string> = {};
  6. if (init?.headers instanceof Headers) {
  7. init.headers.forEach((value, key) => {
  8. requestHeaders[key] = value;
  9. })
  10. }
  11. const response = await axios.request({
  12. url: url.toString(),
  13. method: init?.method || 'GET',
  14. headers: requestHeaders,
  15. data: init?.body,
  16. }).catch((error) => {
  17. console.log('axiosFetch error', error)
  18. if (isAxiosError(error)) {
  19. return {
  20. status: error.response?.status,
  21. statusText: error.response?.statusText,
  22. data: error.response?.data,
  23. headers: error.response?.headers
  24. }
  25. }
  26. throw error;
  27. })
  28. const responseHeaders = new Headers();
  29. if (response.headers) {
  30. for (const [key, value] of Object.entries(response.headers)) {
  31. responseHeaders.set(key, value);
  32. }
  33. }
  34. // 处理204 No Content响应,不设置body
  35. const body = response.status === 204
  36. ? null
  37. : responseHeaders.get('content-type')?.includes('application/json')
  38. ? JSON.stringify(response.data)
  39. : response.data;
  40. return new Response(
  41. body,
  42. {
  43. status: response.status,
  44. statusText: response.statusText,
  45. headers: responseHeaders
  46. }
  47. )
  48. }
  49. // 创建Hono RPC客户端
  50. // @ts-types="node_modules/hono/dist/types/client/types"
  51. export const rpcClient = <T extends any>(aptBaseUrl: string) => {
  52. // @ts-ignore
  53. return hc<T>(aptBaseUrl, {
  54. fetch: axiosFetch
  55. })
  56. }