Updated API connection

This commit is contained in:
Alexis Leboeuf
2026-01-08 14:51:50 +01:00
parent 1b44116936
commit 0e8ba63be5
4 changed files with 100 additions and 12 deletions

View File

@@ -1,27 +1,36 @@
import axios from "axios";
import keycloak from "./keycloak";
const api = axios.create({
baseURL: "http://localhost:8081/api",
// backend listens on 8081 and controllers are mounted at root (no /api prefix)
baseURL: "http://localhost:8081",
headers: {
"Content-Type": "application/json",
},
withCredentials: true,
});
// Simple interceptor to ensure headers object exists; actual token should be set via setAuthToken()
api.interceptors.request.use((config) => {
if (keycloak?.token) {
// eslint-disable-next-line no-param-reassign
config.headers.Authorization = `Bearer ${keycloak.token}`;
console.log(config.headers.Authorization);
}
if (!config.headers) config.headers = {};
return config;
});
// Helpers to set/clear the Authorization header programmatically (call after Keycloak login)
export function setAuthToken(token: string | null) {
if (token) {
api.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} else {
delete api.defaults.headers.common["Authorization"];
}
}
export function clearAuthToken() {
delete api.defaults.headers.common["Authorization"];
}
export const athleteService = {
create: (data: any) => api.post("/athletes/create", data),
getAll: () => api.get("/athletes/all"),
getById: (id: number | string) => api.get(`/athletes/${id}`),
getByKeycloakId: (id: number | string) => api.get(`/athletes/${id}`),
update: (id: number | string, data: any) => api.put(`/athletes/${id}`, data),
delete: (id: number | string) => api.delete(`/athletes/${id}`),
@@ -63,7 +72,7 @@ export const coachService = {
// controller doesn't declare a class-level path consistently; support both common patterns
create: (data: any) => api.post(`/coach/create`, data),
getAll: () => api.get(`/coach/all`),
getById: (id: number | string) => api.get(`/coach/${id}`),
getByKeycloakId: (id: number | string) => api.get(`/coach/${id}`),
update: (id: number | string, data: any) => api.put(`/coach/update/${id}`, data),
delete: (id: number | string) => api.delete(`/coach/delete/${id}`),
@@ -73,7 +82,7 @@ export const coachService = {
};
export const userService = {
getById: (id: number | string) => api.get(`/users/${id}`),
getByKeycloakId: (id: number | string) => api.get(`/users/${id}`),
getAll: () => api.get(`/users`),
};