diff --git a/actions/user-utils/index.js b/actions/user-utils/index.js index 02045de..b932ee8 100644 --- a/actions/user-utils/index.js +++ b/actions/user-utils/index.js @@ -1,13 +1,14 @@ import api from "@/lib/axios"; //get all users -export const getUsers = async () => { +export const getUsers = async ({ page = 1, limit = 10, search = "", role = "all" }) => { try { const response = await api.get("/users", { + params: { page, limit, search, role }, // Pass query parameters headers: { - 'Cache-Control': 'no-cache, no-store, must-revalidate', - 'Pragma': 'no-cache', - 'Expires': '0' + "Cache-Control": "no-cache, no-store, must-revalidate", + Pragma: "no-cache", + Expires: "0", }, }); return response.data; @@ -15,7 +16,7 @@ export const getUsers = async () => { console.error("Error fetching users:", error); throw error; } -} +}; //get user by id export const getUserById = async (id) => { diff --git a/app/api/users/route.js b/app/api/users/route.js index b97169d..85c551f 100644 --- a/app/api/users/route.js +++ b/app/api/users/route.js @@ -1,19 +1,57 @@ - import { NextResponse } from "next/server"; import { User } from "@/models/user-model"; import { dbConnect } from "@/service/mongo"; -export async function GET() { +export async function GET(request) { try { await dbConnect(); - const users = await User.find({}) - .sort({ createdAt: -1 }); + // Extract query parameters + const { searchParams } = new URL(request.url); + const page = parseInt(searchParams.get("page") || "1", 10); + const limit = parseInt(searchParams.get("limit") || "10", 10); + const search = searchParams.get("search") || ""; + const role = searchParams.get("role") || "all"; + + // Calculate skip for pagination + const skip = (page - 1) * limit; + + // Build query + let query = {}; + if (search) { + query.$or = [ + { name: { $regex: search, $options: "i" } }, + { email: { $regex: search, $options: "i" } }, + ]; + } + if (role !== "all") { + query.role = role; + } + + // Fetch users with pagination and filtering + const users = await User.find(query) + .sort({ createdAt: -1 }) + .skip(skip) + .limit(limit); + + // Get total count for pagination + const totalUsers = await User.countDocuments(query); // Convert Mongoose documents to plain objects - const formattedUsers = users.map(user => user.toObject()); + const formattedUsers = users.map((user) => user.toObject()); + + // Prepare pagination data + const pagination = { + currentPage: page, + totalPages: Math.ceil(totalUsers / limit), + totalUsers, + limit, + }; - return NextResponse.json({ users: formattedUsers }, { status: 200 }); + return NextResponse.json( + { users: formattedUsers, pagination }, + { status: 200 } + ); } catch (error) { console.error("Error fetching users:", error); return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 }); diff --git a/app/dashboard/users/page.js b/app/dashboard/users/page.js index 0dcf430..1034f5e 100644 --- a/app/dashboard/users/page.js +++ b/app/dashboard/users/page.js @@ -83,7 +83,7 @@ const UserList = () => { // Fetch users with React Query const { data, error, isLoading } = useQuery({ queryKey: ["users", currentPage], - queryFn: () => getUsers({ page: currentPage, limit }), + queryFn: () => getUsers({ page: currentPage, limit, search: searchTerm, role: roleFilter }), onError: (error) => { if (error.message.includes("Unauthorized")) { toast.error("Please log in to view users.", { @@ -295,7 +295,7 @@ const UserList = () => {

Total Users

-

{users?.length}

+

{data?.users?.length}