You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Hydro/hydro/lib/paginate.js

20 lines
631 B
JavaScript

5 years ago
const { ValidationError } = require('../error');
5 years ago
/**
* @param {import('mongodb').Cursor} cursor
* @param {number} page
* @param {number} pageSize
* @returns {Promise<Array[]>} pageDocs numPages count
*/
4 years ago
async function paginate(cursor, page, pageSize) {
5 years ago
if (page <= 0) throw new ValidationError('page');
5 years ago
const [count, pageDocs] = await Promise.all([
5 years ago
cursor.count(),
5 years ago
cursor.skip((page - 1) * pageSize).limit(pageSize).toArray(),
5 years ago
]);
5 years ago
const numPages = Math.floor((count + pageSize - 1) / pageSize);
return [pageDocs, numPages, count];
4 years ago
}
global.Hydro.lib.paginate = module.exports = paginate;