60 lines
2.0 KiB
TypeScript
60 lines
2.0 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import { handleApiError } from "@/app/api/_utils";
|
|
import { connectToDatabase } from "@/lib/db";
|
|
import { serialize } from "@/lib/serialize";
|
|
import { saveLineupSchema } from "@/lib/validators";
|
|
import { GameModel } from "@/models/Game";
|
|
import { LineupModel } from "@/models/Lineup";
|
|
|
|
export const runtime = "nodejs";
|
|
export const dynamic = "force-dynamic";
|
|
|
|
export async function GET(request: Request) {
|
|
try {
|
|
await connectToDatabase();
|
|
const { searchParams } = new URL(request.url);
|
|
const gameDate = searchParams.get("gameDate");
|
|
const filter = gameDate ? { gameDate: new Date(gameDate) } : {};
|
|
const lineups = await LineupModel.find(filter).sort({ gameDate: -1, lineupNumber: -1 }).lean();
|
|
return NextResponse.json(serialize(lineups));
|
|
} catch (error) {
|
|
return handleApiError(error);
|
|
}
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
await connectToDatabase();
|
|
const payload = saveLineupSchema.parse(await request.json());
|
|
const gameDate = new Date(payload.gameDate);
|
|
const latestForDate = await LineupModel.findOne({ gameDate }).sort({ lineupNumber: -1 }).select("lineupNumber").lean();
|
|
const lineupNumber = (latestForDate?.lineupNumber ?? 0) + 1;
|
|
const lineupPayload = {
|
|
gameDate,
|
|
lineupNumber,
|
|
playerIds: payload.playerIds,
|
|
startingPitcherId: payload.startingPitcherId ?? null,
|
|
battingOrder: payload.battingOrder,
|
|
defensiveAssignments: payload.defensiveAssignments,
|
|
bench: payload.bench,
|
|
notes: payload.notes
|
|
};
|
|
|
|
const lineup = await LineupModel.create(lineupPayload);
|
|
|
|
await GameModel.findOneAndUpdate(
|
|
{ gameDate: lineupPayload.gameDate },
|
|
{
|
|
gameDate: lineupPayload.gameDate,
|
|
activePlayerIds: payload.playerIds,
|
|
startingPitcherId: payload.startingPitcherId ?? null
|
|
},
|
|
{ upsert: true, new: true }
|
|
);
|
|
|
|
return NextResponse.json(serialize(lineup.toObject()), { status: 201 });
|
|
} catch (error) {
|
|
return handleApiError(error);
|
|
}
|
|
}
|