2023-07-20 17:36:08 +02:00
|
|
|
import type { FetchError } from 'ofetch'
|
|
|
|
|
2023-08-01 14:55:03 +02:00
|
|
|
const apiEndpoint =
|
|
|
|
'https://' +
|
|
|
|
(process.dev
|
|
|
|
? useRuntimeConfig().public.apiIp || window.location.hostname
|
|
|
|
: window.location.hostname) +
|
|
|
|
'/yunohost/portalapi'
|
|
|
|
|
|
|
|
export function useApi<T>(
|
2023-07-20 17:36:08 +02:00
|
|
|
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-07-20 17:36:08 +02:00
|
|
|
}
|
|
|
|
|
2023-08-01 14:55:03 +02:00
|
|
|
const query = () => {
|
|
|
|
return $fetch(apiEndpoint + path, {
|
|
|
|
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')
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return Promise.resolve(query()).then(() => result)
|
2023-07-20 17:36:08 +02:00
|
|
|
}
|
2023-07-25 22:25:27 +02:00
|
|
|
|
|
|
|
export interface UserData {
|
|
|
|
username: string
|
|
|
|
fullname: string
|
|
|
|
mail: string
|
2023-08-01 15:13:35 +02:00
|
|
|
mailalias: string[]
|
|
|
|
mailforward: string[]
|
2023-07-25 22:25:27 +02:00
|
|
|
groups: string[]
|
|
|
|
apps: Record<string, { label: string; url: string }>
|
|
|
|
}
|
|
|
|
|
|
|
|
export const useUserData = () => useState<UserData | undefined>('userData')
|
|
|
|
|
|
|
|
export async function useUserInfo() {
|
|
|
|
const userData = useUserData()
|
|
|
|
|
|
|
|
if (!userData.value) {
|
|
|
|
const { data } = await useApi('/me')
|
|
|
|
userData.value = data.value as UserData
|
|
|
|
}
|
2023-08-01 15:13:35 +02:00
|
|
|
|
|
|
|
const update = (data: Partial<UserData>) => {
|
|
|
|
Object.assign(userData.value as UserData, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
userData: userData as Ref<UserData>,
|
|
|
|
update,
|
|
|
|
}
|
2023-07-25 22:25:27 +02:00
|
|
|
}
|