WebIndex/composables/network.ts

55 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>) {
2025-01-13 21:51:37 +08:00
// Const config = useRuntimeConfig()
const { $mitt } = useNuxtApp()
2024-12-01 13:09:44 +08:00
return useFetch(url, {
2025-01-13 21:51:37 +08:00
baseURL: 'https://cantyonion.site',
2024-12-01 13:09:44 +08:00
retry: false,
2025-01-01 23:27:27 +08:00
timeout: 3000,
2024-12-01 13:09:44 +08:00
onRequest({ options }) {
2025-01-13 21:51:37 +08:00
let token: string = ''
2024-12-01 13:09:44 +08:00
if (import.meta.client) {
2025-01-13 21:51:37 +08:00
token = localStorage.getItem('token') || ''
2024-12-01 13:09:44 +08:00
}
2025-01-13 21:51:37 +08:00
if (!options.headers.get('Authorization')) { options.headers.set('Authorization', `Bearer ${token}`) }
2024-12-01 13:09:44 +08:00
},
onResponse({ response }) {
// HTTP状态码2XX/3XX执行否则不执行
if (response.status < 200 || response.status >= 400) {
console.error(`HTTP 错误: ${response.status}`)
}
// 业务code状态码判断
2025-01-13 21:51:37 +08:00
// If (response._data.code !== 200) {
2024-12-01 13:09:44 +08:00
//
// }
},
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}`,
2025-01-13 21:51:37 +08:00
message: response.statusText,
2024-12-01 13:09:44 +08:00
})
},
2025-01-13 21:51:37 +08:00
...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 21:51:37 +08:00
if (result.status.value === 'success') { return result.data.value }
2025-01-13 01:03:16 +08:00
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
}
2025-01-13 21:51:37 +08:00
}