Skip to content

Commit

Permalink
feat: Add api to fetch all users along with pagination
Browse files Browse the repository at this point in the history
  • Loading branch information
ad956 committed Aug 14, 2024
1 parent 271814f commit f3d6f27
Showing 1 changed file with 120 additions and 0 deletions.
120 changes: 120 additions & 0 deletions app/api/admin/users/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import dbConfig from "@utils/db";
import { decrypt } from "@sessions/sessionUtils";
import { Admin, Patient, Receptionist, Hospital, Doctor } from "@models/index";

export interface UserDetails {
id: string;
profile: string;
name: string;
role: string;
username: string;
}

export async function GET(request: Request) {
const session = request.headers.get("Authorization");
if (!session) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}

try {
const token = session.split("Bearer ")[1];
const decryptedUser = await decrypt(token);
const email = decryptedUser.user.email;

await dbConfig();

const adminData = await Admin.findOne({ email });

if (!adminData) {
return Response.json({ error: "Admin not found" }, { status: 404 });
}

// parse query parameters for pagination
const url = new URL(request.url);
const page = parseInt(url.searchParams.get("page") || "1");
const limit = parseInt(url.searchParams.get("limit") || "10");
const skip = (page - 1) * limit;

// base aggregation pipeline
const baseAggregationPipeline = [
{
$project: {
profile: 1,
name: { $concat: ["$firstname", " ", "$lastname"] },
username: 1,
},
},
{ $skip: skip },
{ $limit: limit },
];

// create role-specific pipeline
const createPipelineWithRole = (pipeline: any[], role: string) => [
...pipeline.slice(0, 1),
{ $addFields: { role: role } },
...pipeline.slice(1),
];

// create role-specific pipelines
const patientsPipeline = createPipelineWithRole(
baseAggregationPipeline,
"Patient"
);
const receptionistsPipeline = createPipelineWithRole(
baseAggregationPipeline,
"Receptionist"
);
const doctorsPipeline = createPipelineWithRole(
baseAggregationPipeline,
"Doctor"
);
const hospitalsPipeline = createPipelineWithRole(
baseAggregationPipeline,
"Hospital"
);

// fetch users from each model
const [patients, receptionists, doctors, hospitals] = await Promise.all([
Patient.aggregate(patientsPipeline),
Receptionist.aggregate(receptionistsPipeline),
Doctor.aggregate(doctorsPipeline),
Hospital.aggregate(hospitalsPipeline),
]);

// combine and map results
const allUsers = [...patients, ...receptionists, ...doctors, ...hospitals];
const userDetails: UserDetails[] = allUsers.map((user) => ({
id: user._id.toString(),
profile: user.profile || "",
name: user.name,
role: user.role,
username: user.username,
}));

// pagination count
const [patientCount, receptionistCount, doctorCount, hospitalCount] =
await Promise.all([
Patient.countDocuments(),
Receptionist.countDocuments(),
Doctor.countDocuments(),
Hospital.countDocuments(),
]);
const totalUsers =
patientCount + receptionistCount + doctorCount + hospitalCount;

const paginationMetadata = {
currentPage: page,
pageSize: limit,
totalPages: Math.ceil(totalUsers / limit),
totalCount: totalUsers,
};

return Response.json({
users: userDetails,
pagination: paginationMetadata,
});
} catch (error) {
console.error("Error fetching Users data:", error);
return Response.json({ error: "Internal Server Error" }, { status: 500 });
}
}

0 comments on commit f3d6f27

Please sign in to comment.