api.ts 1.8 KB

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