api.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. return new Response(
  38. responseHeaders.get('content-type')?.includes('application/json') ?
  39. JSON.stringify(response.data) : response.data,
  40. {
  41. status: response.status,
  42. statusText: response.statusText,
  43. headers: responseHeaders
  44. }
  45. )
  46. }
  47. export const authClient = hc<AuthRoutes>('/', {
  48. fetch: axiosFetch,
  49. }).api.v1.auth;
  50. export const userClient = hc<UserRoutes>('/', {
  51. fetch: axiosFetch,
  52. }).api.v1.users;
  53. export const roleClient = hc<RoleRoutes>('/', {
  54. fetch: axiosFetch,
  55. }).api.v1.roles;