yunohost-portal/composables/api.ts

61 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

import type { FetchError } from 'ofetch'
const useApiEndpoint = () => {
return (
'https://' +
(process.dev
? useRuntimeConfig().public.apiIp || window.location.hostname
: window.location.hostname) +
'/yunohost/portalapi'
)
}
2023-08-01 14:55:03 +02:00
export function useApi<T>(
path: string,
{
method = 'GET',
body = undefined,
}: {
method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
body?: Record<string, any>
} = {},
2023-08-01 14:55:03 +02:00
) {
type Resp = {
data: Ref<T | null>
error: Ref<FetchError | null>
}
const result: Resp = {
data: ref(null),
error: ref(null),
}
2023-08-01 14:55:03 +02:00
const query = () => {
return $fetch(useApiEndpoint() + path, {
2023-08-01 14:55:03 +02:00
method,
credentials: 'include',
body,
})
.then((data) => {
result.data.value = data as T
})
.catch(async (e: FetchError) => {
2023-08-01 14:55:03 +02:00
result.error.value = e
if (e.statusCode === 401) {
useIsLoggedIn().value = false
const route = useRoute()
const settings = await useSettings()
if (!(settings.value.public && route.meta.public)) {
navigateTo('/login')
}
2023-08-28 15:08:33 +02:00
} else if (e.statusCode !== 400 && !e.data?.path) {
throw createError({
statusCode: e.statusCode,
statusMessage: e.message,
fatal: true,
})
2023-08-01 14:55:03 +02:00
}
})
}
return Promise.resolve(query()).then(() => result)
}