api.ts 1.7 KB

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