Skip to content

Commit

Permalink
fix(Commons): improve pagination bounds checking
Browse files Browse the repository at this point in the history
  • Loading branch information
jakeaturner committed Mar 29, 2024
1 parent c07418e commit fcacbaf
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 8 deletions.
12 changes: 10 additions & 2 deletions server/api/books.ts
Original file line number Diff line number Diff line change
Expand Up @@ -910,9 +910,17 @@ async function getCommonsCatalog(
});

const totalNumBooks = resultBooks.length;
const offset = getRandomOffset(totalNumBooks);
const offset = getRandomOffset(totalNumBooks, limit);

const randomized = resultBooks.slice(offset, offset + limit);
const upperBound = () => {
if((offset + limit) > totalNumBooks) {
return totalNumBooks;
} else {
return offset + limit;
}
}

const randomized = resultBooks.slice(offset, upperBound());

return res.send({
err: false,
Expand Down
11 changes: 9 additions & 2 deletions server/api/projectfiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1139,9 +1139,16 @@ async function getPublicProjectFiles(
]);

const totalCount = aggRes.length;
const offset = getRandomOffset(totalCount);
const offset = getRandomOffset(totalCount, limit);

const paginatedRes = aggRes.slice(offset, offset + limit);
const upperBound = () => {
if((offset + limit) > totalCount) {
return totalCount;
}
return offset + limit;
}

const paginatedRes = aggRes.slice(offset, upperBound());

return res.send({
err: false,
Expand Down
13 changes: 9 additions & 4 deletions server/util/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -318,12 +318,17 @@ export function getPaginationOffset(page, offsetMultiplier = 25) {
}

/**
* Generates a random number between 0 and max
* @param {Number} max - The maximum number to generate a random offset for
* Generates a random number between 0 and a given limit
* @param {Number} total - The maximum number to generate a random number for
* @param {Number} limit - The limit for the random number
* @returns {Number} - A random number between 0 and max
*/
export function getRandomOffset(max){
return Math.floor(Math.random() * max);
export function getRandomOffset(total, limit) {
if (total <= limit) {
return 0;
}
const maxOffset = Math.max(0, total - limit);
return Math.floor(Math.random() * maxOffset);
}

/**
Expand Down

0 comments on commit fcacbaf

Please sign in to comment.