import type {UseFetchOptions} from "#app"; import {useAuthStore} from "~/store/auth"; export interface Page { content: T[]; size: number; totalElements: number; totalPages: number; number: number; } export interface FieldError { detail: string; fields?: string[]; } export interface ApiError { message: string; statusCode?: number; fieldErrors?: FieldError[] } export const useApi = async (url: string, options?: UseFetchOptions, auth = true) => { const config = useRuntimeConfig(); let headers = {}; if (useAuthStore().authenticated && auth) { let token = useAuthStore().auth.token || null; if (!token || new Date(token.expireAt).getTime() < new Date().getTime()) { console.info("Refresh the session"); await useAuthStore().refreshSession(); } token = useAuthStore().auth.token headers = {'Authorization': `${token.type} ${token.value}`}; } return useFetch(url, { headers: headers, baseURL: config.public.baseURL, ...options }).then(res => { const error = res.error.value; if (error) { if (error.statusCode === 401) { useAuthStore().authenticated = false; } return Promise.reject(error.data); } return Promise.resolve(res.data.value); }, error => { return Promise.reject(error); }) }