Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/teams to join,view,add #164

Merged
merged 9 commits into from
Dec 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 }
);
}
}
66 changes: 66 additions & 0 deletions app/api/teams/create-team/route.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import dbConnect from "../../../../lib/dbConnect";
import { teamSchema } from "../../../../model/Schema/teamSchema";
import { TeamModel } from "../../../../model/Team";
import UserModel from "../../../../model/User";
import { getServerSession } from "next-auth";
import { authOptions } from "../../../../lib/authOptions";
import { NextResponse } from "next/server";

export async function POST(request) {

// Get session from next-auth using NextResponse for the App Directory
const session = await getServerSession(authOptions);

// Ensure the session is valid
if (!session || !session.user) {
return NextResponse.json(
{ success: false, message: "Unauthorized" },
{ status: 401 }
);
}
try {
const { teamname, game, role, rank, server, language, players } =
await request.json();

// Validate the data using the Zod schema
const parsedData = teamSchema.parse({
teamname,
game,
role,
rank,
server,
language,
players,
});

await dbConnect();

// Validate users exist for the team players
const playerUsernames = parsedData.players.map((player) => player.trim());
const users = await UserModel.find({ username: { $in: playerUsernames } });

if (users.length !== playerUsernames.length) {
return NextResponse.json(
{ success: false, message: "Some usernames do not exist." },
{ status: 400 }
);
}

const playerIds = users.map((user) => user._id);

// Create a new team with the validated and formatted data
const formattedData = { ...parsedData, players: playerIds };
const team = await TeamModel.create(formattedData);

return NextResponse.json(
{ success: true, message: "Team created successfully.", team },
{ status: 201 }
);
} catch (error) {
console.error("Error creating team:", error);
return NextResponse.json(
{ success: false, message: "Error creating team", error: error.message },
{ status: 500 }
);
}
}
69 changes: 0 additions & 69 deletions app/api/teams/create-team/route.jsx

This file was deleted.

73 changes: 49 additions & 24 deletions app/api/teams/get-request/route.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,65 @@
import dbConnect from "../../../../lib/dbConnect";
import { TeamModel } from "../../../../model/Team";
import { getServerSession } from "next-auth";
import { authOptions } from "../../../../lib/authOptions";
import { NextResponse } from "next/server";

export async function GET(req) {
await dbConnect();
const { searchParams } = new URL(req.url);
const teamId = searchParams.get("teamId");
export async function GET(request) {
try {

if (!teamId) {
return new Response(
JSON.stringify({ success: false, message: "Team ID is required" }),
{ status: 400 },
);
}
const session = await getServerSession(authOptions);

try {
const team = await TeamModel.findById(teamId).populate(
"requests",
"username",
);
if (!session || !session.user) {
return new NextResponse(
JSON.stringify({ success: false, message: "Unauthorized" }),
{ status: 401 }
);
}

const teamId = request.nextUrl.searchParams.get("teamId");
if (!teamId) {
return new NextResponse(
JSON.stringify({ success: false, message: "Team ID is required" }),
{ status: 400 }
);
}

const userId = session.user._id; // Extract user ID from session

await dbConnect();
const team = await TeamModel.findById(teamId).populate("requests", "username email");

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

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

// Return the list of requests
return new NextResponse(
JSON.stringify({
success: true,
message: "Team requests fetched successfully",
requests: team.requests,
}),
{ status: 200 }
);

} catch (error) {
console.error("Error fetching requests:", error);
return new Response(
JSON.stringify({ success: false, message: "Error fetching requests" }),
{ status: 500 },
console.error("Error fetching team requests:", error);
return new NextResponse(
JSON.stringify({ success: false, message: "Server error" }),
{ status: 500 }
);
}
}
43 changes: 28 additions & 15 deletions app/api/teams/send-request/route.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,54 @@
import dbConnect from "../../../../lib/dbConnect";
import { getServerSession } from "next-auth";
import { authOptions } from "../../../../lib/authOptions";
import { TeamModel } from "../../../../model/Team";
import UserModel from "../../../../model/User";
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 } = await request.json();

export async function POST(req) {
await dbConnect();
const { teamId, userId } = await req.json();

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

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

// Check if the user has already requested to join
if (team.requests.includes(userId)) {
return new Response(
JSON.stringify({ success: false, message: "Request already sent" }),
{ status: 400 },
JSON.stringify({ success: false, message: "You have already requested to join this team" }),
{ status: 400 }
);
}

// Add the user to the team's requests
team.requests.push(userId);
await team.save();

return new Response(
JSON.stringify({ success: true, message: "Request sent successfully" }),
{ status: 200 },
JSON.stringify({ success: true, message: "Join request sent successfully" }),
{ status: 200 }
);
} catch (error) {
console.error("Error sending request:", error);
console.error("Error making join request:", error);
return new Response(
JSON.stringify({ success: false, message: "Error sending request" }),
{ status: 500 },
JSON.stringify({ success: false, message: "Server error" }),
{ status: 500 }
);
}
}
8 changes: 7 additions & 1 deletion model/Team.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ const TeamSchema = new mongoose.Schema({
rank: { type: String, required: true },
server: { type: String, required: true },
language: { type: String, required: true },
players: [{ type: String, required: true }],
players: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "UserModel",
required: true,
},
],
requests: [
{
type: mongoose.Schema.Types.ObjectId,
Expand Down
Loading