Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
19 changes: 7 additions & 12 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Suspense } from "react";
import ExploreBtn from "@/components/ExploreBtn";
import EventCard from "@/components/EventCard";
import SearchFilters from "@/components/SearchFilters"; // Added missing import
import Footer from "@/components/Footer"; // Added missing import
import SearchFilters from "@/components/SearchFilters";
import Footer from "@/components/Footer";
import { IEvent } from "@/database";
import { cacheLife } from "next/cache";
import { getAllEvents } from "@/lib/actions/event.actions";

interface PageProps {
Expand All @@ -15,12 +15,9 @@ interface PageProps {
}

const Page = async ({ searchParams }: PageProps) => {

// 1. Resolve search variables from the URL router interface
const resolvedParams = await searchParams;

// 2. Fixed Destructuring: Receives plain array directly from your updated action
const events = await getAllEvents({
const { events } = await getAllEvents({
query: resolvedParams.query,
mode: resolvedParams.mode,
tag: resolvedParams.tag,
Expand All @@ -33,15 +30,15 @@ const Page = async ({ searchParams }: PageProps) => {

<ExploreBtn />

{/* 3. Insert the newly generated Search and Filter component bar */}
<div className="mt-10">
<SearchFilters />
<Suspense fallback={<div className="w-full h-16 animate-pulse rounded-xl bg-white/5" />}>
<SearchFilters />
</Suspense>
</div>

<div className="mt-20 space-y-7">
<h3>Featured Events</h3>

{/* 4. Display list layout conditionally or deliver clean placeholder states */}
{events && events.length > 0 ? (
<ul className="events">
{events.map((event: IEvent) => (
Expand All @@ -51,10 +48,8 @@ const Page = async ({ searchParams }: PageProps) => {
))}
</ul>
) : (
/* Smooth Contextual Empty State displayed dynamically */
<div className="flex flex-col items-center justify-center text-center p-12 border border-dashed border-gray-300 rounded-2xl max-w-xl mx-auto bg-white/50">
<h4 className="text-lg font-semibold text-gray-800 mb-1">No events found</h4>
{/* Fixed Linting Error: Escaped the apostrophe here */}
<p className="text-sm text-gray-500 max-w-xs">
We couldn&apos;t find any listings matching your search constraints. Try checking your spelling or adjusting filters.
</p>
Expand Down
116 changes: 111 additions & 5 deletions lib/actions/event.actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,21 @@ import Event from "@/database/event.model";

const escapeRegex = (text: string) => text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');

export async function getAllEvents(filters?: { query?: string; mode?: string; tag?: string }) {
type EventFilters = {
query?: string;
mode?: string;
tag?: string;
sortBy?: "date_asc" | "date_desc" | "name_asc" | "name_desc" | "popularity";
};

export async function getAllEvents(
filters?: EventFilters,
page = 1,
limit?: number
) {
try {
await connectToDatabase();
const queryCondition: any = {};
const queryCondition: Record<string, unknown> = {};

if (filters?.query) {
const safeQuery = escapeRegex(filters.query);
Expand All @@ -27,11 +38,106 @@ export async function getAllEvents(filters?: { query?: string; mode?: string; ta
queryCondition.tags = { $regex: new RegExp(`^${safeTag}$`, 'i') };
}

const events = await Event.find(queryCondition).sort({ createdAt: -1 });
return JSON.parse(JSON.stringify(events));
const safePage = Number.isInteger(page) && page > 0 ? page : 1;
const safeLimit = limit && Number.isInteger(limit) && limit > 0 ? Math.min(limit, 100) : undefined;
const skip = safeLimit ? (safePage - 1) * safeLimit : 0;
Comment thread
SatyamPandey-07 marked this conversation as resolved.
Outdated

if (filters?.sortBy === "popularity") {
const Booking = (await import("@/database/booking.model")).default;
const total = await Event.countDocuments(queryCondition);
const pipeline: object[] = [
{ $match: queryCondition },
{
$lookup: {
from: Booking.collection.name,
localField: "_id",
foreignField: "eventId",
as: "bookings",
},
},
{ $addFields: { bookingCount: { $size: "$bookings" } } },
{ $sort: { bookingCount: -1, createdAt: -1 } },
{ $project: { bookings: 0, bookingCount: 0 } },
];

if (safeLimit) {
pipeline.push({ $skip: skip }, { $limit: safeLimit });
}

const events = await Event.aggregate(pipeline);
const totalPages = safeLimit ? Math.max(1, Math.ceil(total / safeLimit)) : 1;

return {
events: JSON.parse(JSON.stringify(events)),
total,
totalPages,
currentPage: safePage,
};
}

const sortField =
filters?.sortBy === "date_asc"
? { date: 1 as const }
: filters?.sortBy === "date_desc"
? { date: -1 as const }
: filters?.sortBy === "name_asc"
? { title: 1 as const }
: filters?.sortBy === "name_desc"
? { title: -1 as const }
: { createdAt: -1 as const };

const total = await Event.countDocuments(queryCondition);
let query = Event.find(queryCondition).sort(sortField);

if (safeLimit) {
query = query.skip(skip).limit(safeLimit);
}

const events = await query;
const totalPages = safeLimit ? Math.max(1, Math.ceil(total / safeLimit)) : 1;

return {
events: JSON.parse(JSON.stringify(events)),
total,
totalPages,
currentPage: safePage,
};

} catch (error) {
console.error('Error fetching events:', error);
return [];
return {
events: [],
total: 0,
totalPages: 1,
currentPage: 1,
};
}
}

export async function getSimilarEventsBySlug(slug: string, limit = 3) {
try {
await connectToDatabase();

const currentEvent = await Event.findOne({ slug }).select("type tags").lean();

if (!currentEvent) {
return [];
}

const safeLimit = Number.isInteger(limit) && limit > 0 ? Math.min(limit, 12) : 3;
const similarEvents = await Event.find({
slug: { $ne: slug },
$or: [
{ type: currentEvent.type },
{ tags: { $in: currentEvent.tags } },
],
})
.sort({ createdAt: -1 })
.limit(safeLimit);

return JSON.parse(JSON.stringify(similarEvents));
} catch (error) {
console.error("Error fetching similar events:", error);
return [];
}
}
1 change: 1 addition & 0 deletions lib/mongodb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ async function connectToDatabase(): Promise<Mongoose> {
if (!cached.promise) {
const options = {
bufferCommands: false, // Disable command buffering for better error handling
serverSelectionTimeoutMS: 5000,
Comment thread
SatyamPandey-07 marked this conversation as resolved.
};

cached.promise = mongoose.connect(MONGODB_URI!, options);
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
Expand Down