58 lines
1.9 KiB
TypeScript
58 lines
1.9 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 creation of a default calendar for an authenticated user.
|
|
*
|
|
* This function checks if the user already has a default calendar named "Calendrier principal".
|
|
* If such a calendar exists, it returns the existing calendar.
|
|
* Otherwise, it creates a new default calendar for the user.
|
|
*
|
|
* @param req - The incoming request object.
|
|
* @returns A JSON response containing the existing or newly created calendar, or an error message.
|
|
*
|
|
* @throws Will return a 401 status if the user is not authenticated.
|
|
* @throws Will return a 500 status if there is a server error during the calendar creation process.
|
|
*/
|
|
export async function POST(req: NextRequest) {
|
|
const session = await getServerSession(authOptions);
|
|
|
|
if (!session?.user?.username) {
|
|
return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
|
|
}
|
|
|
|
try {
|
|
// Vérifier si l'utilisateur a déjà un calendrier par défaut
|
|
const existingCalendar = await prisma.calendar.findFirst({
|
|
where: {
|
|
userId: session.user.username,
|
|
name: "Calendrier principal",
|
|
},
|
|
});
|
|
|
|
if (existingCalendar) {
|
|
return NextResponse.json(existingCalendar);
|
|
}
|
|
|
|
// Créer un calendrier par défaut
|
|
const calendar = await prisma.calendar.create({
|
|
data: {
|
|
name: "Calendrier principal",
|
|
color: "#0082c9",
|
|
description: "Calendrier principal",
|
|
userId: session.user.username,
|
|
},
|
|
});
|
|
|
|
return NextResponse.json(calendar, { status: 201 });
|
|
} catch (error) {
|
|
console.error(
|
|
"Erreur lors de la création du calendrier par défaut:",
|
|
error
|
|
);
|
|
return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
|
|
}
|
|
}
|