Skip to content
Open
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
11 changes: 6 additions & 5 deletions actions/user-utils/index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
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;
} catch (error) {
console.error("Error fetching users:", error);
throw error;
}
}
};

//get user by id
export const getUserById = async (id) => {
Expand Down
50 changes: 44 additions & 6 deletions app/api/users/route.js
Original file line number Diff line number Diff line change
@@ -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 });
Expand Down
4 changes: 2 additions & 2 deletions app/dashboard/users/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.", {
Expand Down Expand Up @@ -295,7 +295,7 @@ const UserList = () => {
</div>
<div>
<p className="text-sm text-gray-500">Total Users</p>
<p className="text-xl font-bold">{users?.length}</p>
<p className="text-xl font-bold">{data?.users?.length}</p>
</div>
</div>
<div className="bg-white p-4 rounded-lg shadow-md flex items-center">
Expand Down