mirror of
https://github.com/YunoHost/yunohost-portal.git
synced 2024-09-03 20:06:23 +02:00
use $fetch for useApi
This commit is contained in:
parent
b82638f247
commit
7a18f54de9
1 changed files with 34 additions and 24 deletions
|
@ -1,7 +1,13 @@
|
||||||
import type { AsyncData } from 'nuxt/app'
|
|
||||||
import type { FetchError } from 'ofetch'
|
import type { FetchError } from 'ofetch'
|
||||||
|
|
||||||
export async function useApi<T>(
|
const apiEndpoint =
|
||||||
|
'https://' +
|
||||||
|
(process.dev
|
||||||
|
? useRuntimeConfig().public.apiIp || window.location.hostname
|
||||||
|
: window.location.hostname) +
|
||||||
|
'/yunohost/portalapi'
|
||||||
|
|
||||||
|
export function useApi<T>(
|
||||||
path: string,
|
path: string,
|
||||||
{
|
{
|
||||||
method = 'GET',
|
method = 'GET',
|
||||||
|
@ -10,30 +16,34 @@ export async function useApi<T>(
|
||||||
method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
|
method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
|
||||||
body?: Record<string, any>
|
body?: Record<string, any>
|
||||||
} = {},
|
} = {},
|
||||||
): Promise<AsyncData<T, FetchError | null>> {
|
) {
|
||||||
const host = window.location.hostname
|
type Resp = {
|
||||||
const apiEndpoint =
|
data: Ref<T | null>
|
||||||
'https://' +
|
error: Ref<FetchError | null>
|
||||||
(process.dev ? useRuntimeConfig().public.apiIp || host : host) +
|
}
|
||||||
'/yunohost/portalapi'
|
const result: Resp = {
|
||||||
|
data: ref(null),
|
||||||
|
error: ref(null),
|
||||||
|
}
|
||||||
|
|
||||||
const result = await useFetch(apiEndpoint + path, {
|
const query = () => {
|
||||||
headers: {
|
return $fetch(apiEndpoint + path, {
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'X-Requested-With': '',
|
|
||||||
},
|
|
||||||
method,
|
method,
|
||||||
credentials: 'include',
|
credentials: 'include',
|
||||||
body,
|
body,
|
||||||
})
|
})
|
||||||
|
.then((data) => {
|
||||||
const error = result.error.value
|
result.data.value = data as T
|
||||||
if (error && error.statusCode === 401) {
|
})
|
||||||
|
.catch((e: FetchError) => {
|
||||||
|
result.error.value = e
|
||||||
|
if (e.statusCode === 401) {
|
||||||
useIsLoggedIn().value = false
|
useIsLoggedIn().value = false
|
||||||
navigateTo('/login')
|
navigateTo('/login')
|
||||||
}
|
}
|
||||||
|
})
|
||||||
return result as AsyncData<T, FetchError | null>
|
}
|
||||||
|
return Promise.resolve(query()).then(() => result)
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserData {
|
export interface UserData {
|
||||||
|
|
Loading…
Reference in a new issue