Files
boussole-pluss/frontend/composables/fetch-api.ts
Nicolas Doby 5d884b1be6 feat: review backend and frontend
- update to the latest version of Java/SpringBoot
- update to the latest version NuxtJS
- add account/password update
- add account creation
- add account password reset
- add bundle to regroup questions and add default questions on user creation
- add bundle creation
2024-07-09 14:37:43 +02:00

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);
})
}