Files
peworkshop/app/api/teams/[teamId]/route.js
T

72 lines
2.1 KiB
JavaScript

import { query, queryOne } from "@/lib/db";
import { cookies } from "next/headers";
import { verifyToken } from "@/app/api/auth/[...nextauth]/route";
export const dynamic = "force-dynamic"; // Disable static rendering and caching
export async function GET(request, context) {
try {
// Use our custom token verification
const cookieStore = await cookies();
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
if (!sessionToken) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
const userData = verifyToken(sessionToken);
if (!userData) {
return Response.json({ error: "Invalid session" }, { status: 401 });
}
// FIXED: Always await context.params before accessing properties
// This approach ensures we properly handle the promise before accessing teamId
const params = await Promise.resolve(context.params);
const teamId = params?.teamId;
// Validate teamId
if (!teamId || isNaN(parseInt(teamId, 10))) {
return Response.json({ error: "Invalid team ID" }, { status: 400 });
}
const team = await queryOne("SELECT * FROM teams WHERE id = ?", [teamId]);
if (!team) {
return Response.json({ error: "Team not found" }, { status: 404 });
}
// Use a fresh query to get the latest team members each time
const members = await query(
"SELECT id, username FROM users WHERE team_id = ? ORDER BY username ASC",
[teamId]
);
const timestamp = new Date().toISOString(); // Add timestamp for debugging
// Add additional cache-busting headers
return Response.json(
{
success: true,
team,
members,
refreshed: timestamp,
lastUpdated: team.last_updated || timestamp,
},
{
status: 200,
headers: {
"Cache-Control": "no-store, must-revalidate, max-age=0",
Pragma: "no-cache",
Expires: "0",
},
}
);
} catch (error) {
console.error("Team fetch error:", error);
return Response.json(
{ error: "Failed to fetch team data" },
{ status: 500 }
);
}
}