40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import type { FetchResponse } from "ofetch"
|
|
|
|
export function useAPI(route: string = "/") {
|
|
return `https://api.door.svitan.dev${route}`
|
|
}
|
|
|
|
export async function handleRequestError({ error }: { error: Error }) {
|
|
const toast = useToast()
|
|
toast.add({
|
|
title: "Error occurred",
|
|
description: error.message,
|
|
color: "error",
|
|
})
|
|
}
|
|
|
|
export function handleResponse<T>(
|
|
success: (response: FetchResponse<T>) => Promise<void> | void
|
|
) {
|
|
const token = useToken()
|
|
const toast = useToast()
|
|
|
|
return async function ({ response }: { response: FetchResponse<T> }) {
|
|
console.log(response)
|
|
// console.log(await response.text())
|
|
if (response.status === 200) {
|
|
await success(response.clone())
|
|
} else if (response.status === 401) {
|
|
toast.add({ title: "Token not valid", color: "error" })
|
|
token.value = ""
|
|
navigateTo("/token")
|
|
} else {
|
|
toast.add({
|
|
title: "Error occurred",
|
|
description: await response.text(),
|
|
color: "error",
|
|
})
|
|
}
|
|
}
|
|
}
|