Updating
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
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 }).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 lineupPayload = {
|
||||
gameDate: new Date(payload.gameDate),
|
||||
playerIds: payload.playerIds,
|
||||
startingPitcherId: payload.startingPitcherId ?? null,
|
||||
battingOrder: payload.battingOrder,
|
||||
defensiveAssignments: payload.defensiveAssignments,
|
||||
bench: payload.bench,
|
||||
notes: payload.notes
|
||||
};
|
||||
|
||||
const lineup = await LineupModel.findOneAndUpdate({ gameDate: lineupPayload.gameDate }, lineupPayload, {
|
||||
upsert: true,
|
||||
new: true,
|
||||
runValidators: true
|
||||
}).lean();
|
||||
|
||||
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), { status: 201 });
|
||||
} catch (error) {
|
||||
return handleApiError(error);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user