|
| 1 | +import type { $Fetch } from 'ofetch' |
| 2 | + |
| 3 | +import { useRuntimeConfig } from '#app' |
| 4 | +import { ofetch } from 'ofetch' |
| 5 | + |
| 6 | +type HttpStatusErrorHandler = (message: string, statusCode: number) => void |
| 7 | +let httpStatusErrorHandler: HttpStatusErrorHandler |
| 8 | + |
| 9 | +let http: $Fetch |
| 10 | + |
| 11 | +export function setupHttp() { |
| 12 | + if (http) |
| 13 | + return http |
| 14 | + |
| 15 | + const config = useRuntimeConfig() |
| 16 | + const baseURL = config.public.apiBase as string |
| 17 | + |
| 18 | + http = ofetch.create({ |
| 19 | + baseURL, |
| 20 | + headers: { 'Content-Type': 'application/json' }, |
| 21 | + async onRequest({ options }) { |
| 22 | + const token = localStorage.getItem('token') |
| 23 | + |
| 24 | + options.headers = { |
| 25 | + ...options.headers, |
| 26 | + ...(token && { Authorization: `Bearer ${token}` }), |
| 27 | + } |
| 28 | + }, |
| 29 | + async onResponseError({ response }) { |
| 30 | + const { message } = response._data |
| 31 | + if (Array.isArray(message)) { |
| 32 | + message.forEach((item) => { |
| 33 | + httpStatusErrorHandler?.(item, response.status) |
| 34 | + }) |
| 35 | + } |
| 36 | + else { |
| 37 | + httpStatusErrorHandler?.(message, response.status) |
| 38 | + } |
| 39 | + return Promise.reject(response._data) |
| 40 | + }, |
| 41 | + retry: 3, |
| 42 | + retryDelay: 1000, |
| 43 | + }) |
| 44 | +} |
| 45 | + |
| 46 | +export function injectHttpStatusErrorHandler(handler: HttpStatusErrorHandler) { |
| 47 | + httpStatusErrorHandler = handler |
| 48 | +} |
| 49 | + |
| 50 | +export function getHttp() { |
| 51 | + if (!http) { |
| 52 | + throw new Error('HTTP client not initialized. Call setupHttp first.') |
| 53 | + } |
| 54 | + return http |
| 55 | +} |
0 commit comments