53 lines
1.5 KiB
TypeScript
53 lines
1.5 KiB
TypeScript
import type { AsyncData, UseFetchOptions } from '#app'
|
||
|
||
export function requestCore<DataT>(url: string, options: UseFetchOptions<DataT>) {
|
||
// const config = useRuntimeConfig()
|
||
return useFetch(url, {
|
||
baseURL: "https://cantyonion.site",
|
||
retry: false,
|
||
onRequest({ options }) {
|
||
let token: string = ""
|
||
if (import.meta.client) {
|
||
token = localStorage.getItem("token") || ""
|
||
}
|
||
if (!options.headers.get('Authorization'))
|
||
options.headers.set('Authorization', `Bearer ${token}`)
|
||
},
|
||
onResponse({ response }) {
|
||
// HTTP状态码2XX/3XX执行,否则不执行
|
||
if (response.status < 200 || response.status >= 400) {
|
||
console.error(`HTTP 错误: ${response.status}`)
|
||
return
|
||
}
|
||
// 业务code状态码判断
|
||
// if (response._data.code !== 200) {
|
||
//
|
||
// }
|
||
},
|
||
onResponseError({ response }) {
|
||
emitter.emit('eventBus', {
|
||
level: 'error',
|
||
title: `HTTP错误:${response.status}`,
|
||
message: response.statusText
|
||
})
|
||
},
|
||
...options
|
||
})
|
||
}
|
||
|
||
export function get<DataT, ErrorT>(url: string, options?: UseFetchOptions<DataT>): () => Promise<DataT> {
|
||
let result: AsyncData<DataT, ErrorT> | null = null
|
||
|
||
return async (): Promise<DataT> => {
|
||
if (result != null) {
|
||
await result.refresh()
|
||
return result.data.value
|
||
}
|
||
|
||
result = await requestCore(url, {
|
||
method: 'GET',
|
||
...options,
|
||
}) as AsyncData<DataT, ErrorT>
|
||
return result.data.value
|
||
}
|
||
} |