Neah-Enkun/front/app/api/calendars/[id]/events/[eventId]/route.ts

271 lines
7.8 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { prisma } from "@/lib/prisma";
/**
* Handles the GET request to retrieve a specific event from a calendar.
*
* @param req - The incoming Next.js request object.
* @param params - An object containing the route parameters.
* @param params.id - The ID of the calendar.
* @param params.eventId - The ID of the event.
* @returns A JSON response containing the event data or an error message.
*
* The function performs the following steps:
* 1. Checks if the user is authenticated.
* 2. Verifies that the calendar exists and belongs to the authenticated user.
* 3. Verifies that the event exists and belongs to the specified calendar.
* 4. Returns the event data if all checks pass.
*
* Possible error responses:
* - 401: User is not authenticated.
* - 403: User is not authorized to access the calendar.
* - 404: Calendar or event not found.
* - 500: Server error occurred while retrieving the event.
*/
export async function GET(
req: NextRequest,
{ params }: { params: { id: string; eventId: string } }
) {
const session = await getServerSession(authOptions);
if (!session?.user?.username) {
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
}
try {
// Vérifier que le calendrier appartient à l'utilisateur
const calendar = await prisma.calendar.findUnique({
where: {
id: params.id,
},
});
if (!calendar) {
return NextResponse.json(
{ error: "Calendrier non trouvé" },
{ status: 404 }
);
}
if (calendar.userId !== session.user.username) {
return NextResponse.json({ error: "Non autorisé" }, { status: 403 });
}
const event = await prisma.event.findUnique({
where: {
id: params.eventId,
},
});
if (!event) {
return NextResponse.json(
{ error: "Événement non trouvé" },
{ status: 404 }
);
}
// Vérifier que l'événement appartient bien au calendrier
if (event.calendarId !== params.id) {
return NextResponse.json(
{ error: "Événement non trouvé dans ce calendrier" },
{ status: 404 }
);
}
return NextResponse.json(event);
} catch (error) {
console.error("Erreur lors de la récupération de l'événement:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}
/**
* Handles the PUT request to update an event in a calendar.
*
* @param req - The incoming request object.
* @param params - The route parameters containing the calendar ID and event ID.
* @returns A JSON response indicating the result of the update operation.
*
* The function performs the following steps:
* 1. Retrieves the server session to check if the user is authenticated.
* 2. Verifies that the calendar belongs to the authenticated user.
* 3. Checks if the event exists and belongs to the specified calendar.
* 4. Validates the request payload to ensure required fields are present.
* 5. Updates the event with the provided data.
* 6. Returns the updated event or an appropriate error response.
*
* Possible error responses:
* - 401: User is not authenticated.
* - 403: User is not authorized to update the calendar.
* - 404: Calendar or event not found.
* - 400: Validation error for missing required fields.
* - 500: Server error during the update process.
*/
export async function PUT(
req: NextRequest,
{ params }: { params: { id: string; eventId: string } }
) {
const session = await getServerSession(authOptions);
if (!session?.user?.username) {
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
}
try {
// Vérifier que le calendrier appartient à l'utilisateur
const calendar = await prisma.calendar.findUnique({
where: {
id: params.id,
},
});
if (!calendar) {
return NextResponse.json(
{ error: "Calendrier non trouvé" },
{ status: 404 }
);
}
if (calendar.userId !== session.user.username) {
return NextResponse.json({ error: "Non autorisé" }, { status: 403 });
}
// Vérifier que l'événement existe et appartient au calendrier
const existingEvent = await prisma.event.findUnique({
where: {
id: params.eventId,
},
});
if (!existingEvent) {
return NextResponse.json(
{ error: "Événement non trouvé" },
{ status: 404 }
);
}
if (existingEvent.calendarId !== params.id) {
return NextResponse.json(
{ error: "Événement non trouvé dans ce calendrier" },
{ status: 404 }
);
}
const { title, description, start, end, location, isAllDay } =
await req.json();
// Validation
if (!title) {
return NextResponse.json(
{ error: "Le titre est requis" },
{ status: 400 }
);
}
if (!start || !end) {
return NextResponse.json(
{ error: "Les dates de début et de fin sont requises" },
{ status: 400 }
);
}
const updatedEvent = await prisma.event.update({
where: {
id: params.eventId,
},
data: {
title,
description,
start: new Date(start),
end: new Date(end),
location,
isAllDay: isAllDay || false,
},
});
return NextResponse.json(updatedEvent);
} catch (error) {
console.error("Erreur lors de la mise à jour de l'événement:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}
/**
* Handles the DELETE request to remove an event from a calendar.
*
* @param req - The incoming Next.js request object.
* @param params - An object containing the parameters from the request URL.
* @param params.id - The ID of the calendar.
* @param params.eventId - The ID of the event to be deleted.
* @returns A JSON response indicating the result of the deletion operation.
*
* @throws Will return a 401 status if the user is not authenticated.
* @throws Will return a 404 status if the calendar or event is not found.
* @throws Will return a 403 status if the user is not authorized to delete the event.
* @throws Will return a 500 status if there is a server error during the deletion process.
*/
export async function DELETE(
req: NextRequest,
{ params }: { params: { id: string; eventId: string } }
) {
const session = await getServerSession(authOptions);
if (!session?.user?.username) {
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
}
try {
// Vérifier que le calendrier appartient à l'utilisateur
const calendar = await prisma.calendar.findUnique({
where: {
id: params.id,
},
});
if (!calendar) {
return NextResponse.json(
{ error: "Calendrier non trouvé" },
{ status: 404 }
);
}
if (calendar.userId !== session.user.username) {
return NextResponse.json({ error: "Non autorisé" }, { status: 403 });
}
// Vérifier que l'événement existe et appartient au calendrier
const existingEvent = await prisma.event.findUnique({
where: {
id: params.eventId,
},
});
if (!existingEvent) {
return NextResponse.json(
{ error: "Événement non trouvé" },
{ status: 404 }
);
}
if (existingEvent.calendarId !== params.id) {
return NextResponse.json(
{ error: "Événement non trouvé dans ce calendrier" },
{ status: 404 }
);
}
await prisma.event.delete({
where: {
id: params.eventId,
},
});
return new NextResponse(null, { status: 204 });
} catch (error) {
console.error("Erreur lors de la suppression de l'événement:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}