107 lines
2.5 KiB
TypeScript
107 lines
2.5 KiB
TypeScript
import { useState, useEffect } from "react";
|
|
import { Event } from "@prisma/client";
|
|
|
|
export function useCalendarEvents(calendarId: string, start: Date, end: Date) {
|
|
const [events, setEvents] = useState<Event[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState<Error | null>(null);
|
|
|
|
// Charger les événements
|
|
const fetchEvents = async () => {
|
|
if (!calendarId) return;
|
|
|
|
try {
|
|
setLoading(true);
|
|
setError(null);
|
|
|
|
const response = await fetch(
|
|
`/api/calendars/${calendarId}/events?` +
|
|
`start=${start.toISOString()}&end=${end.toISOString()}`
|
|
);
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Erreur ${response.status}: ${await response.text()}`);
|
|
}
|
|
|
|
const data = await response.json();
|
|
setEvents(data);
|
|
} catch (err) {
|
|
console.error("Erreur lors du chargement des événements:", err);
|
|
setError(err as Error);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
// Créer un événement
|
|
const createEvent = async (eventData: any) => {
|
|
const response = await fetch(`/api/calendars/${calendarId}/events`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify(eventData),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
throw new Error(errorText);
|
|
}
|
|
|
|
return await response.json();
|
|
};
|
|
|
|
// Mettre à jour un événement
|
|
const updateEvent = async (eventData: any) => {
|
|
const response = await fetch(
|
|
`/api/calendars/${calendarId}/events/${eventData.id}`,
|
|
{
|
|
method: "PUT",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify(eventData),
|
|
}
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
throw new Error(errorText);
|
|
}
|
|
|
|
return await response.json();
|
|
};
|
|
|
|
// Supprimer un événement
|
|
const deleteEvent = async (eventId: string) => {
|
|
const response = await fetch(
|
|
`/api/calendars/${calendarId}/events/${eventId}`,
|
|
{
|
|
method: "DELETE",
|
|
}
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
throw new Error(errorText);
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
// Charger les événements quand le calendrier ou les dates changent
|
|
useEffect(() => {
|
|
fetchEvents();
|
|
}, [calendarId, start.toISOString(), end.toISOString()]);
|
|
|
|
return {
|
|
events,
|
|
loading,
|
|
error,
|
|
refresh: fetchEvents,
|
|
createEvent,
|
|
updateEvent,
|
|
deleteEvent,
|
|
};
|
|
}
|