api-helper-kit
Version:
Rohan api helper kit
51 lines (42 loc) • 1.15 kB
JavaScript
const paginate = async (
model,
page = 1,
limit = 10,
filter = {},
sortField = "",
sortOrder = 1
) => {
// Ensure page and limit are integers
page = parseInt(page);
limit = parseInt(limit);
// Validate page and limit
if (page < 1) page = 1;
if (limit < 1) limit = 10;
// Ensure sortOrder is either 1 (ascending) or -1 (descending)
sortOrder = sortOrder === -1 ? -1 : 1;
// Calculate the number of documents to skip
const skip = (page - 1) * limit;
try {
// Prepare sort object
const sort = sortField ? { [sortField]: sortOrder } : {};
// Query the database with filter, skip, limit, and sorting
const [items, total] = await Promise.all([
model.find(filter).skip(skip).limit(limit).sort(sort).exec(),
model.countDocuments(filter),
]);
// Calculate total pages
const totalPages = Math.ceil(total / limit);
return {
items,
totalItems: total,
currentPage: page,
totalPages,
itemsPerPage: limit,
};
} catch (err) {
throw new Error(`Error during pagination: ${err.message}`);
}
};
module.exports = {
usePaginate: paginate,
};