WebIndex/composables/network.ts

57 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-12-01 13:09:44 +08:00
import type { AsyncData, UseFetchOptions } from '#app'
2024-11-17 11:45:08 +08:00
2024-12-01 13:09:44 +08:00
export function requestCore<DataT>(url: string, options: UseFetchOptions<DataT>) {
// const config = useRuntimeConfig()
2024-12-18 08:42:26 +08:00
const {$mitt} = useNuxtApp()
2024-12-01 13:09:44 +08:00
return useFetch(url, {
baseURL: "https://cantyonion.site",
retry: false,
2025-01-01 23:27:27 +08:00
timeout: 3000,
2024-12-01 13:09:44 +08:00
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 }) {
2024-12-18 08:42:26 +08:00
$mitt.emit('eventBus', {
2024-12-01 13:09:44 +08:00
level: 'error',
title: `HTTP错误${response.status}`,
message: response.statusText
})
},
...options
2024-11-17 11:45:08 +08:00
})
2024-12-01 13:09:44 +08:00
}
2024-11-17 11:45:08 +08:00
2024-12-01 13:09:44 +08:00
export function get<DataT, ErrorT>(url: string, options?: UseFetchOptions<DataT>): () => Promise<DataT> {
let result: AsyncData<DataT, ErrorT> | null = null
2024-11-17 11:45:08 +08:00
2024-12-01 13:09:44 +08:00
return async (): Promise<DataT> => {
if (result != null) {
await result.refresh()
2025-01-13 01:03:16 +08:00
if (result.status.value === 'success')
return result.data.value
throw result.error
2024-12-01 13:09:44 +08:00
}
2024-11-17 11:45:08 +08:00
2024-12-01 13:09:44 +08:00
result = await requestCore(url, {
method: 'GET',
...options,
}) as AsyncData<DataT, ErrorT>
return result.data.value
}
2024-11-17 11:45:08 +08:00
}