75 lines
1.4 KiB
TypeScript
75 lines
1.4 KiB
TypeScript
import { createFetch } from '@vueuse/core'
|
|
import { API_BASE_URL } from '~/CONSTANT'
|
|
|
|
export const authCode = ref(
|
|
localStorage.getItem('authCode')
|
|
|| sessionStorage.getItem('authCode')
|
|
|| '',
|
|
)
|
|
|
|
export const baseFetch = createFetch({
|
|
baseUrl: API_BASE_URL,
|
|
options: {
|
|
async beforeFetch({ options }) {
|
|
options.headers = {
|
|
...options.headers,
|
|
Authorization: `${authCode.value}`,
|
|
}
|
|
return { options }
|
|
},
|
|
|
|
},
|
|
fetchOptions: {
|
|
mode: 'cors',
|
|
},
|
|
|
|
})
|
|
|
|
export async function doCheckOnline() {
|
|
let resp = null
|
|
try {
|
|
resp = await baseFetch('/ping', {
|
|
timeout: 2000,
|
|
})
|
|
const { error } = resp
|
|
if (error.value)
|
|
throw new Error(error.value)
|
|
const status = resp.response.value?.status
|
|
if (!status) {
|
|
return false
|
|
}
|
|
if (status === 200) {
|
|
return true
|
|
}
|
|
else if (status >= 400 && status < 500) {
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
catch (err) {
|
|
if (resp?.response.value?.status === 401) {
|
|
return true
|
|
}
|
|
console.error(err)
|
|
return false
|
|
}
|
|
}
|
|
|
|
export const useBackendOnline = createSharedComposable(() => {
|
|
const isOnline = ref(true)
|
|
|
|
const useCheckInterval = useIntervalFn(() => {
|
|
doCheckOnline().then((online) => {
|
|
isOnline.value = online
|
|
})
|
|
}, 5000, {
|
|
immediate: true,
|
|
immediateCallback: true,
|
|
})
|
|
useCheckInterval.resume()
|
|
|
|
return {
|
|
isOnline,
|
|
}
|
|
})
|