Files
n3wt-school/Front-End/src/app/actions/planningAction.js
2025-04-15 19:41:42 +02:00

97 lines
2.6 KiB
JavaScript

import { BE_PLANNING_PLANNINGS_URL, BE_PLANNING_EVENTS_URL } from '@/utils/Url';
const requestResponseHandler = async (response) => {
const body = response.status !== 204 ? await response?.json() : {};
console.log(response);
if (response.ok) {
return body;
}
// Throw an error with the JSON body containing the form errors
const error = new Error(body?.errorMessage || 'Une erreur est survenue');
error.details = body;
throw error;
};
const getData = (url) => {
return fetch(`${url}`).then(requestResponseHandler);
};
const createDatas = (url, newData, csrfToken) => {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
},
body: JSON.stringify(newData),
credentials: 'include',
}).then(requestResponseHandler);
};
const updateDatas = (url, updatedData, csrfToken) => {
return fetch(`${url}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
},
body: JSON.stringify(updatedData),
credentials: 'include',
}).then(requestResponseHandler);
};
const removeDatas = (url, csrfToken) => {
return fetch(`${url}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
},
credentials: 'include',
}).then(requestResponseHandler);
};
export const fetchPlannings = () => {
return getData(`${BE_PLANNING_PLANNINGS_URL}`);
};
export const getPlanning = (id) => {
return getData(`${BE_PLANNING_PLANNINGS_URL}/${id}`);
};
export const createPlanning = (newData, csrfToken) => {
return createDatas(`${BE_PLANNING_PLANNINGS_URL}`, newData, csrfToken);
};
export const updatePlanning = (id, newData, csrfToken) => {
return updateDatas(`${BE_PLANNING_PLANNINGS_URL}/${id}`, newData, csrfToken);
};
export const deletePlanning = (id, csrfToken) => {
return removeDatas(`${BE_PLANNING_PLANNINGS_URL}/${id}`, csrfToken);
};
export const fetchEvents = () => {
return getData(`${BE_PLANNING_EVENTS_URL}`);
};
export const getEvent = (id) => {
return getData(`${BE_PLANNING_EVENTS_URL}/${id}`);
};
export const createEvent = (newData, csrfToken) => {
return createDatas(`${BE_PLANNING_EVENTS_URL}`, newData, csrfToken);
};
export const updateEvent = (id, newData, csrfToken) => {
return updateDatas(`${BE_PLANNING_EVENTS_URL}/${id}`, newData, csrfToken);
};
export const deleteEvent = (id, csrfToken) => {
return removeDatas(`${BE_PLANNING_EVENTS_URL}/${id}`, csrfToken);
};
export const fetchUpcomingEvents = () => {
return getData(`${BE_PLANNING_EVENTS_URL}/upcoming`);
};