yunohost-portal/composables/api.ts

57 lines
1.2 KiB
TypeScript
Raw 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((e: FetchError) => {
result.error.value = e
if (e.statusCode === 401) {
useIsLoggedIn().value = false
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)
}