WebIndex/composables/network.ts
2025-01-13 01:03:16 +08:00

57 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { AsyncData, UseFetchOptions } from '#app'
export function requestCore<DataT>(url: string, options: UseFetchOptions<DataT>) {
// const config = useRuntimeConfig()
const {$mitt} = useNuxtApp()
return useFetch(url, {
baseURL: "https://cantyonion.site",
retry: false,
timeout: 3000,
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 }) {
$mitt.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()
if (result.status.value === 'success')
return result.data.value
throw result.error
}
result = await requestCore(url, {
method: 'GET',
...options,
}) as AsyncData<DataT, ErrorT>
return result.data.value
}
}