Skip to content

Commit

Permalink
Update api of accept team request
Browse files Browse the repository at this point in the history
  • Loading branch information
denishdev committed Dec 24, 2024
1 parent 127286d commit fc4d7c9
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions app/api/teams/accept-request/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { getServerSession } from "next-auth";
import { authOptions } from "../../../../lib/authOptions";
import { TeamModel } from "../../../../model/Team";
import dbConnect from "../../../../lib/dbConnect";

export async function POST(request) {
const session = await getServerSession(authOptions);

if (!session || !session.user) {
return new Response(
JSON.stringify({ success: false, message: "Unauthorized" }),
{ status: 401 }
);
}

const userId = session.user._id; // Extract user ID from the session
const { teamId, playerId } = await request.json();

if (!teamId || !playerId) {
return new Response(
JSON.stringify({ success: false, message: "Team ID and Player ID are required" }),
{ status: 400 }
);
}

await dbConnect();

try {
const team = await TeamModel.findById(teamId);

if (!team) {
return new Response(
JSON.stringify({ success: false, message: "Team not found" }),
{ status: 404 }
);
}

// Check if the authenticated user is a member of the team
const isPlayerInTeam = team.players.some((player) => player.toString() === userId);
if (!isPlayerInTeam) {
return new Response(
JSON.stringify({ success: false, message: "Forbidden: You are not a member of this team" }),
{ status: 403 }
);
}

// Add the new player to the team
if (!team.players.includes(playerId)) {
team.players.push(playerId);
await team.save();
}

return new Response(
JSON.stringify({ success: true, message: "Player added successfully" }),
{ status: 200 }
);
} catch (error) {
console.error("Error adding player:", error);
return new Response(
JSON.stringify({ success: false, message: "Server error" }),
{ status: 500 }
);
}
}

0 comments on commit fc4d7c9

Please sign in to comment.