Skip to content

Commit

Permalink
Merge pull request #157 from vaibhavgarg25/main
Browse files Browse the repository at this point in the history
Feat: completely migrated the website's backend to mongoDb
  • Loading branch information
SkySingh04 authored Dec 31, 2024
2 parents f542752 + 6937603 commit b831098
Show file tree
Hide file tree
Showing 9 changed files with 301 additions and 283 deletions.
73 changes: 36 additions & 37 deletions app/(default)/api/events/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
setDoc
} from "firebase/firestore";
import { NextResponse } from "next/server";
import Eventmodel from "@/models/Events";
import connectMongoDB from "@/lib/dbConnect";
import { v4 as uuidv4 } from 'uuid';

// Helper function to validate event data
Expand Down Expand Up @@ -46,11 +48,10 @@ const validateEvent = (event: any) => {

// GET request
export async function GET(request: Request) {
await connectMongoDB()
try {
const eventsCollection = collection(db, "events");
const eventSnapshot = await getDocs(eventsCollection);
const data = eventSnapshot.docs.map((doc) => doc.data());
const eventsList = data.map((event: any) => ({
const eventSnapshot = await Eventmodel.find()
const eventsList = eventSnapshot.map((event: any) => ({
id: event.id,
eventName: event.eventName,
description: event.description,
Expand Down Expand Up @@ -83,56 +84,41 @@ export async function GET(request: Request) {
// POST request
export async function POST(request: Request) {
try {
await connectMongoDB();
const newEvent = await request.json();
const validationErrors = validateEvent(newEvent);

if (validationErrors.length > 0) {
console.error("Validation errors:", validationErrors);
return NextResponse.json(
{ error: "Validation failed", details: validationErrors },
{ status: 400 }
);
}

const eventId = uuidv4();
const currentDate = new Date().toISOString();
const { eventName, eventDate, lastDateOfRegistration, description, imageURL, registrationLink } = newEvent;

await setDoc(doc(db, "events", eventId), {
const newEventData = new Eventmodel({
id: eventId,
eventName,
eventDate,
lastDateOfRegistration,
description,
imageURL,
registrationLink,
...newEvent,
dateCreated: currentDate,
dateModified: currentDate,
});

const savedEvent = await newEventData.save();
return NextResponse.json({ id: eventId }, { status: 201 });
} catch (error) {
if (error instanceof Error) {
console.error("Error details:", error.message);
return NextResponse.json(
{ error: "An error occurred", details: error.message },
{ status: 500 }
);
} else {
console.error("Unknown error:", error);
return NextResponse.json(
{ error: "An unknown error occurred" },
{ status: 500 }
);
}
console.error("Error occurred during event creation:", error);
return NextResponse.json(
{ error: "An error occurred while creating the event", details: error instanceof Error ? error.message : "Unknown error" },
{ status: 500 }
);
}
}

// PUT request
export async function PUT(request: Request) {
await connectMongoDB()
try {
const { searchParams } = new URL(request.url);
const eventid = searchParams.get("eventid");

console.log(eventid)
if (!eventid) {
return NextResponse.json(
{ error: "Event ID is required" },
Expand All @@ -150,10 +136,23 @@ export async function PUT(request: Request) {
);
}

await updateDoc(doc(db, "events", eventid), {
...updatedEvent,
dateModified: new Date().toISOString(),
});
const result = await Eventmodel.findOneAndUpdate(
{ id:eventid },
{
$set: {
...updatedEvent,
dateModified: new Date().toISOString(),
}
},
{ new: true }
);

if (!result) {
return NextResponse.json(
{ error: "Event not found" },
{ status: 404 }
);
}

return NextResponse.json({ id: eventid }, { status: 200 });
} catch (error) {
Expand All @@ -172,9 +171,9 @@ export async function PUT(request: Request) {
}
}
}

// DELETE request
export async function DELETE(request: Request) {
await connectMongoDB()
try {
const { searchParams } = new URL(request.url);
const eventid = searchParams.get("eventid");
Expand All @@ -186,7 +185,7 @@ export async function DELETE(request: Request) {
);
}

await deleteDoc(doc(db, "events", eventid));
await Eventmodel.deleteOne({id:eventid})
return NextResponse.json({ message: "Event deleted successfully" }, { status: 200 });
} catch (error) {
if (error instanceof Error) {
Expand Down
38 changes: 19 additions & 19 deletions app/(default)/api/hustle/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
getDoc,
} from "firebase/firestore";
import { app } from "@/Firebase";
import connectMongoDB from "@/lib/dbConnect";
import PbhustleModel from "@/models/PbHustel";

interface ContestRanking {
rank: number;
Expand All @@ -32,8 +34,8 @@ interface LeaderboardData {

export async function POST() {
try {
console.log("Initializing Firestore connection.");
const db = getFirestore(app);
console.log("Initializing mongodb connection.");
await connectMongoDB()

const API_URL =
process.env.VJUDGE_CONTEST_API ||
Expand All @@ -49,11 +51,11 @@ export async function POST() {
const url = `https://vjudge.net/contest/${ccode}#rank`;
console.log(`Contest URL: ${url}`);

const leaderboardRef = doc(db, "hustle", "leaderboard");

console.log("Fetching existing leaderboard data from Firestore.");
const leaderboardDoc = await getDoc(leaderboardRef);
const leaderboardDoc = await PbhustleModel.findOne({name:"leaderboard"})

const existingData = leaderboardDoc.data() as LeaderboardData | undefined;
const existingData = leaderboardDoc as LeaderboardData | undefined;
console.log("Existing leaderboard data:", existingData);

const lastContestCode = existingData?.lastContestCode;
Expand Down Expand Up @@ -92,12 +94,12 @@ export async function POST() {
console.log("Extracted rankings:", latest);
await browser.close();

const latestRef = doc(db, "hustle", "latest");
console.log("Updating latest contest results in Firestore.");
await setDoc(latestRef, {
await PbhustleModel.findOneAndUpdate({
name:"latest",
results: latest,
updateTime: new Date(),
});
});

let rankings: LeaderboardUser[] = existingData?.rankings || [];
console.log("Existing rankings:", rankings);
Expand Down Expand Up @@ -129,7 +131,8 @@ export async function POST() {

console.log("Final rankings:", rankings);
console.log("Updating leaderboard in Firestore.");
await setDoc(leaderboardRef, {
await PbhustleModel.findOneAndUpdate({
name:"leaderboard",
rankings,
updatedAt: new Date(),
lastContestCode: ccode,
Expand All @@ -147,25 +150,22 @@ export async function POST() {

export async function GET() {
try {
console.log("Initializing Firestore connection for GET request.");
const db = getFirestore();

await connectMongoDB()
console.log("Fetching latest contest results from Firestore.");
const latestDoc = await getDoc(doc(db, "hustle", "latest"));

const latestDoc = await PbhustleModel.findOne({name:"latest"})
console.log("Fetching leaderboard data from Firestore.");
const leaderboardDoc = await getDoc(doc(db, "hustle", "leaderboard"));
const leaderboardDoc = await PbhustleModel.findOne({name:"leaderboard"})

console.log("Fetched data successfully:", {
latest: latestDoc.data(),
leaderboard: leaderboardDoc.data(),
latest: latestDoc,
leaderboard: leaderboardDoc,
});

return NextResponse.json({
message: "Fetched hustle data successfully",
data: {
latest: latestDoc.data(),
leaderboard: leaderboardDoc.data(),
latest: latestDoc,
leaderboard: leaderboardDoc,
},
});
} catch (error) {
Expand Down
Loading

0 comments on commit b831098

Please sign in to comment.