2025-01-16 07:40:06 +00:00
|
|
|
|
|
|
|
import { useRuntimeConfig } from '#app'
|
|
|
|
import { ofetch } from 'ofetch'
|
2025-01-16 08:18:38 +00:00
|
|
|
import {message} from '@/components/x-message/useMessage.js'
|
2025-01-17 08:56:13 +00:00
|
|
|
import {authStore} from "@/stores/auth/index.js";
|
2025-01-16 08:18:38 +00:00
|
|
|
let httpStatusErrorHandler
|
2025-01-16 07:40:06 +00:00
|
|
|
|
2025-01-16 08:18:38 +00:00
|
|
|
let http
|
2025-01-16 07:40:06 +00:00
|
|
|
|
|
|
|
export function setupHttp() {
|
|
|
|
if (http)
|
|
|
|
return http
|
|
|
|
|
|
|
|
const config = useRuntimeConfig()
|
2025-01-16 08:18:38 +00:00
|
|
|
const baseURL = config.public.NUXT_PUBLIC_API_BASE
|
2025-01-17 08:56:13 +00:00
|
|
|
const {token}= authStore()
|
2025-01-16 07:40:06 +00:00
|
|
|
http = ofetch.create({
|
|
|
|
baseURL,
|
|
|
|
headers: { 'Content-Type': 'application/json' },
|
|
|
|
async onRequest({ options }) {
|
|
|
|
options.headers = {
|
|
|
|
...options.headers,
|
2025-01-17 08:56:13 +00:00
|
|
|
Authorization:token.value
|
2025-01-16 07:40:06 +00:00
|
|
|
}
|
|
|
|
},
|
2025-01-16 08:18:38 +00:00
|
|
|
async onResponse({ response }) {
|
|
|
|
if (response._data.status===1){
|
2025-01-17 06:07:19 +00:00
|
|
|
message.error(response._data.msg)
|
2025-01-16 08:18:38 +00:00
|
|
|
}
|
|
|
|
},
|
2025-01-16 07:40:06 +00:00
|
|
|
async onResponseError({ response }) {
|
|
|
|
const { message } = response._data
|
|
|
|
if (Array.isArray(message)) {
|
|
|
|
message.forEach((item) => {
|
|
|
|
httpStatusErrorHandler?.(item, response.status)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
httpStatusErrorHandler?.(message, response.status)
|
|
|
|
}
|
|
|
|
return Promise.reject(response._data)
|
|
|
|
},
|
|
|
|
retry: 3,
|
|
|
|
retryDelay: 1000,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2025-01-16 08:18:38 +00:00
|
|
|
export function injectHttpStatusErrorHandler(handler) {
|
2025-01-16 07:40:06 +00:00
|
|
|
httpStatusErrorHandler = handler
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getHttp() {
|
|
|
|
if (!http) {
|
|
|
|
throw new Error('HTTP client not initialized. Call setupHttp first.')
|
|
|
|
}
|
|
|
|
return http
|
|
|
|
}
|