This repository has been archived on 2024-01-23. You can view files and clone it, but cannot push or open issues/pull-requests.
API/src/controllers/adminController.ts

41 lines
1.1 KiB
TypeScript

import { Request, Response } from "express";
import { User } from "../models/user";
import {
ADMIN_MAX_USERS_PER_PAGE,
MONGODB_IGNORED_FIELDS_USER,
} from "../utils/constants";
export async function GetAllUsers(req: Request, res: Response) {
try {
const pageSize = ADMIN_MAX_USERS_PER_PAGE;
// Get the current page number (default: 1)
const page = parseInt(req.query.page as string, pageSize) || 1;
// Calculate the skipping (skip) based on the current page
const skip = (page - 1) * pageSize;
// Get the total number of users
const totalUsers = await User.countDocuments({}).lean();
// Calculate the total number of pages
const totalPages = Math.ceil(totalUsers / pageSize);
// Query for the current page with limit and skip
const users = await User.find({})
.lean()
.select(MONGODB_IGNORED_FIELDS_USER)
.skip(skip)
.limit(pageSize);
// Respond with users and page information
res.json({
users,
totalPages,
});
} catch (error) {
console.error("Error fetching users:", error);
res.status(500).json({ error: "Internal Server Error" });
}
}