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

182 lines
5.5 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 GET requests to retrieve a calendar by its ID.
*
* @param req - The incoming request object.
* @param params - An object containing the route parameters.
* @param params.id - The ID of the calendar to retrieve.
* @returns A JSON response containing the calendar data if found and authorized,
* or an error message with the appropriate HTTP status code.
*
* - 401: If the user is not authenticated.
* - 403: If the user is not authorized to access the calendar.
* - 404: If the calendar is not found.
* - 500: If there is a server error during the retrieval process.
*/
export async function GET(
req: NextRequest,
{ params }: { params: { id: string } }
) {
const session = await getServerSession(authOptions);
if (!session?.user?.username) {
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
}
try {
const calendar = await prisma.calendar.findUnique({
where: {
id: params.id,
},
});
if (!calendar) {
return NextResponse.json(
{ error: "Calendrier non trouvé" },
{ status: 404 }
);
}
// Vérification que l'utilisateur est bien le propriétaire
if (calendar.userId !== session.user.username) {
return NextResponse.json({ error: "Non autorisé" }, { status: 403 });
}
return NextResponse.json(calendar);
} catch (error) {
console.error("Erreur lors de la récupération du calendrier:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}
/**
* Handles the PUT request to update a calendar.
*
* @param req - The incoming request object.
* @param params - An object containing the route parameters.
* @param params.id - The ID of the calendar to update.
* @returns A JSON response with the updated calendar data or an error message.
*
* @throws {401} If the user is not authenticated.
* @throws {404} If the calendar is not found.
* @throws {403} If the user is not authorized to update the calendar.
* @throws {400} If the calendar name is not provided.
* @throws {500} If there is a server error during the update process.
*/
export async function PUT(
req: NextRequest,
{ params }: { params: { id: string } }
) {
const session = await getServerSession(authOptions);
if (!session?.user?.username) {
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
}
try {
// Vérifier que le calendrier existe et appartient à l'utilisateur
const existingCalendar = await prisma.calendar.findUnique({
where: {
id: params.id,
},
});
if (!existingCalendar) {
return NextResponse.json(
{ error: "Calendrier non trouvé" },
{ status: 404 }
);
}
if (existingCalendar.userId !== session.user.username) {
return NextResponse.json({ error: "Non autorisé" }, { status: 403 });
}
const { name, color, description } = await req.json();
// Validation
if (!name) {
return NextResponse.json(
{ error: "Le nom du calendrier est requis" },
{ status: 400 }
);
}
const updatedCalendar = await prisma.calendar.update({
where: {
id: params.id,
},
data: {
name,
color,
description,
},
});
return NextResponse.json(updatedCalendar);
} catch (error) {
console.error("Erreur lors de la mise à jour du calendrier:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}
/**
* Handles the DELETE request to remove a calendar by its ID.
*
* @param req - The incoming Next.js request object.
* @param params - An object containing the route parameters.
* @param params.id - The ID of the calendar to be deleted.
* @returns A JSON response indicating the result of the deletion operation.
*
* - If the user is not authenticated, returns a 401 status with an error message.
* - If the calendar does not exist, returns a 404 status with an error message.
* - If the calendar does not belong to the authenticated user, returns a 403 status with an error message.
* - If the calendar is successfully deleted, returns a 204 status with no content.
* - If an error occurs during the deletion process, returns a 500 status with an error message.
*/
export async function DELETE(
req: NextRequest,
{ params }: { params: { id: string } }
) {
const session = await getServerSession(authOptions);
if (!session?.user?.username) {
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
}
try {
// Vérifier que le calendrier existe et appartient à l'utilisateur
const existingCalendar = await prisma.calendar.findUnique({
where: {
id: params.id,
},
});
if (!existingCalendar) {
return NextResponse.json(
{ error: "Calendrier non trouvé" },
{ status: 404 }
);
}
if (existingCalendar.userId !== session.user.username) {
return NextResponse.json({ error: "Non autorisé" }, { status: 403 });
}
await prisma.calendar.delete({
where: {
id: params.id,
},
});
return new NextResponse(null, { status: 204 });
} catch (error) {
console.error("Erreur lors de la suppression du calendrier:", error);
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
}
}