Skip to content

Commit

Permalink
refactor prisma to mongoose
Browse files Browse the repository at this point in the history
  • Loading branch information
aneesazc committed Jul 24, 2024
1 parent e417833 commit ae90c9b
Show file tree
Hide file tree
Showing 11 changed files with 211 additions and 139 deletions.
59 changes: 29 additions & 30 deletions app/api/create-tournament/route.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,38 @@
import { PrismaClient } from '@prisma/client';
import { NextResponse } from 'next/server';
import dbConnect from '../../../lib/dbConnect';
import Tournament from '../../../model/Tournament';

const prisma = new PrismaClient();
export async function POST(req) {
try {
await dbConnect();

export async function POST(req, res) {
{
const { tournamentName, selectedPlatform, participantType, selectedTimezone, size } = req.body;
const { tournamentName, selectedPlatform, participantType, selectedTimezone, size } = await req.json();

try {
await dbConnect();
const existingTournament = await Tournament.findOne({ tournamentName });

const existingTournament = await prisma.tournament.findFirst({
where: { tournamentName },
});
if (existingTournament) {
return NextResponse.json({ message: 'Tournament already exists' }, { status: 409 });
}

if (existingTournament) {
return res.status(409).json({ message: 'Tournament already exists' });
}
const newTournament = new Tournament({
tournamentName,
platform: selectedPlatform,
participantType,
timezone: selectedTimezone,
size: parseInt(size, 10),
});

const newTournament = await prisma.tournament.create({
data: {
tournamentName,
platform: selectedPlatform,
participantType,
timezone: selectedTimezone,
size: parseInt(size, 10),
},
});
await newTournament.save();

res.status(200).json({ message: 'Tournament created successfully', tournament: newTournament });
} catch (error) {
console.error('Error creating tournament:', error);
res.status(500).json({ message: 'An error occurred while creating the tournament' });
} finally {
await prisma.$disconnect();
}
return NextResponse.json(
{ message: 'Tournament created successfully', tournament: newTournament },
{ status: 201 }
);
} catch (error) {
console.error('Error creating tournament:', error);
return NextResponse.json(
{ message: 'An error occurred while creating the tournament' },
{ status: 500 }
);
}
}
}
24 changes: 7 additions & 17 deletions app/api/games/route.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
import { PrismaClient } from '@prisma/client';
import { NextResponse } from 'next/server';
import dbConnect from '../../../lib/dbConnect';
import Games from '../../../model/Games';

const prisma = new PrismaClient();

export async function GET(req, res) {
export async function GET(req) {
await dbConnect();

try {
const gameData = await prisma.games.findMany();
const existingGames = [];

for (const game of gameData) {
const existingGame = await prisma.games.findUnique({
where: { name: game.name },
});
existingGames.push(existingGame);
}
const gameData = await Games.find().lean();

res.status(200).json(existingGames);
return NextResponse.json(gameData, { status: 200 });
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
} finally {
await prisma.$disconnect();
console.error('Error fetching games:', error);
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}
27 changes: 16 additions & 11 deletions app/api/tournaments/[id]/route.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();
import dbConnect from "../../../../lib/dbConnect";
import Tournament from '../../../../model/Tournament';
import Games from '../../../../model/Games';
import Organizer from '../../../../model/Organizer';

export async function GET(request, { params }) {
await dbConnect();

try {
const id = params.id;
const tournament = await prisma.tournament.findUnique({
where: { id },
include: {
game: true,
organizer: true,
},
});

// Ensure all models are registered
Games;
Organizer;

const tournament = await Tournament.findById(id)
.populate('gameId')
.populate('organizerId')
.lean();

if (tournament) {
return NextResponse.json(tournament);
Expand All @@ -21,6 +26,6 @@ export async function GET(request, { params }) {
}
} catch (error) {
console.error('Error fetching tournament:', error);
return NextResponse.json({ error: 'Error fetching tournament' }, { status: 500 });
return NextResponse.json({ error: 'Error fetching tournament', details: error.message }, { status: 500 });
}
}
36 changes: 20 additions & 16 deletions app/api/tournaments/route.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();
import dbConnect from "../../../lib/dbConnect";
import Tournament from '../../../model/Tournament';
import Games from '../../../model/Games';
import Organizer from '../../../model/Organizer';

export async function GET(request) {
await dbConnect();

const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get('page') || '1');
const limit = parseInt(searchParams.get('limit') || '10');
Expand All @@ -12,24 +15,25 @@ export async function GET(request) {

const skip = (page - 1) * limit;

const where = {};
if (gameType) where.gameType = gameType;
if (organizerId) where.organizerId = organizerId;
const query = {};
if (gameType) query.gameType = gameType;
if (organizerId) query.organizerId = organizerId;

try {
console.log('Fetching tournaments with params:', { page, limit, gameType, organizerId });

const tournaments = await prisma.tournament.findMany({
where,
include: {
game: true,
organizer: true,
},
skip,
take: limit,
});
// Ensure models are registered
Games;
Organizer;

const tournaments = await Tournament.find(query)
.populate('gameId', 'name category gameBannerPhoto')
.populate('organizerId', 'orgName bannerPhoto')
.skip(skip)
.limit(limit)
.lean();

const total = await prisma.tournament.count({ where });
const total = await Tournament.countDocuments(query);

console.log(`Found ${tournaments.length} tournaments out of ${total} total`);

Expand Down
42 changes: 27 additions & 15 deletions app/tournaments/[id]/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,32 @@ import Image from 'next/image';
import Link from 'next/link';
import { CalendarIcon, ClockIcon, PersonIcon, CrossCircledIcon, LockClosedIcon } from '@radix-ui/react-icons';
import { Trophy, DollarSign, Users, Shield } from 'lucide-react';
import prisma from '../../../lib/db';
import dbConnect from '../../../lib/dbConnect';
import Tournament from '../../../model/Tournament';

async function getTournament(id) {
const tournament = await prisma.tournament.findUnique({
where: { id },
include: {
game: true,
organizer: true,
},
});
return tournament;
await dbConnect();
if (!id) {
console.error('Tournament ID is undefined');
return null;
}
try {
const tournament = await Tournament.findById(id)
.populate('gameId')
.populate('organizerId')
.lean();
return tournament ? JSON.parse(JSON.stringify(tournament)) : null;
} catch (error) {
console.error('Error fetching tournament:', error);
return null;
}
}

export default async function TournamentPage({ params }) {
if (!params || !params.id) {
return <div>Invalid tournament ID</div>;
}

const tournament = await getTournament(params.id);

if (!tournament) {
Expand All @@ -27,7 +39,7 @@ export default async function TournamentPage({ params }) {
<div className="bg-gray-800 rounded-lg overflow-hidden shadow-xl">
<div className="relative h-64 sm:h-80 lg:h-96">
<Image
src={tournament.game.gameBannerPhoto || "/placeholder-tournament.jpg"}
src={tournament.gameId?.gameBannerPhoto || "/placeholder-tournament.jpg"}
alt={tournament.tournamentName}
layout="fill"
objectFit="cover"
Expand Down Expand Up @@ -84,20 +96,20 @@ export default async function TournamentPage({ params }) {
<h2 className="text-xl font-semibold mb-4">Host</h2>
<div className="flex items-center">
<Image
src={tournament.organizer.bannerPhoto || "/placeholder-organizer.jpg"}
alt={tournament.organizer.orgName}
src={tournament.organizerId?.bannerPhoto || "/placeholder-organizer.jpg"}
alt={tournament.organizerId?.orgName || "Organizer"}
width={50}
height={50}
className="rounded-full"
/>
<span className="ml-4 text-lg">{tournament.organizer.orgName}</span>
<span className="ml-4 text-lg">{tournament.organizerId?.orgName || "Unknown Organizer"}</span>
</div>
</div>
</div>

<div className="mt-8">
<h2 className="text-xl font-semibold mb-4">Description</h2>
<p>{tournament.game.profile}</p>
<p>{tournament.gameId?.profile || "No description available"}</p>
</div>

<div className="mt-8">
Expand All @@ -120,7 +132,7 @@ export default async function TournamentPage({ params }) {
</div>

<div className="mt-8 flex justify-center">
<Link href={`/register/${tournament.id}`} className="bg-blue-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors">
<Link href={`/register/${tournament._id}`} className="bg-blue-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-blue-700 transition-colors">
Register for Tournament
</Link>
</div>
Expand Down
21 changes: 13 additions & 8 deletions components/TournamentSection.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ export default function TournamentSection({ filters }) {
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4 gap-2 transition-all">
{filteredTournaments.map((tournament) => (
<Link
key={tournament.id}
href={`/tournaments/${tournament.id}`}
key={tournament._id}
href={`/tournaments/${tournament._id}`}
className="hover:scale-105 transition-all"
>
<TournamentCard {...tournament} />
Expand All @@ -93,8 +93,8 @@ function TournamentCard({
prize,
slots,
registeredNumber,
game,
organizer,
gameId,
organizerId,
}) {
const getStatus = () => {
const now = new Date();
Expand Down Expand Up @@ -132,7 +132,9 @@ function TournamentCard({
{status}
</span>
<Image
src={game.gameBannerPhoto || "/placeholder-tournament.jpg"}
src={
(gameId && gameId.gameBannerPhoto) || "/placeholder-tournament.jpg"
}
alt={tournamentName}
width={500}
height={200}
Expand All @@ -155,14 +157,17 @@ function TournamentCard({
<div className="mt-4 p-2 flex items-center justify-between text-sm bg-gray-700 rounded">
<div className="flex items-center">
<Image
src={organizer.bannerPhoto || "/placeholder-organizer.jpg"}
alt={organizer.orgName}
src={
(organizerId && organizerId.bannerPhoto) ||
"/placeholder-organizer.jpg"
}
alt={organizerId ? organizerId.orgName : "Organizer"}
width={20}
height={20}
className="rounded-full"
/>
<span className="ml-2 text-sm text-gray-300">
{organizer.orgName}
{organizerId ? organizerId.orgName : "Unknown Organizer"}
</span>
</div>
<div className="text-xs text-gray-300">Host</div>
Expand Down
14 changes: 14 additions & 0 deletions model/Games.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// model/Games.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const GamesSchema = new Schema({
name: { type: String, unique: true },
category: String,
profile: String,
gameBannerPhoto: String
});

const Games = mongoose.models.Games || mongoose.model('Games', GamesSchema);

module.exports = Games;
19 changes: 19 additions & 0 deletions model/Organizer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const OrganizerSchema = new Schema({
orgName: { type: String, unique: true },
orgEmail: { type: String, unique: true },
description: String,
bannerPhoto: String,
twoFactorActivated: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now },
socials: [String],
members: [String]
});

// module.exports = mongoose.model('Organizer', OrganizerSchema);

const Organizer = mongoose.models.Organizer || mongoose.model('Organizer', OrganizerSchema);

module.exports = Organizer;
Loading

0 comments on commit ae90c9b

Please sign in to comment.