boussole-pluss/frontend/composables/fetch-api.ts

56 lines
1.4 KiB
TypeScript

import type {UseFetchOptions} from "#app";
import {useAuthStore} from "~/store/auth";
export interface Page<T> {
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[]
}
function instanceOfApiError(object: any): object is ApiError {
return object !== undefined && 'message' in object;
}
export const useApi = async (url: string, options?: UseFetchOptions<any>, auth = true) => {
const config = useRuntimeConfig();
let headers = {};
console.info(`isLogged: ${useAuthStore().isLoggedIn}, isSessionExpired: ${useAuthStore().isSessionExpired}`);
if (useAuthStore().isLoggedIn && auth) {
if (useAuthStore().isSessionExpired) {
await useAuthStore().refreshSession();
}
const 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);
})
}