Skip to content

Instantly share code, notes, and snippets.

@OtayNacef
Last active November 24, 2021 10:01
Show Gist options
  • Save OtayNacef/345be3db0ef1bc8c6121fc1a5fe9e6b6 to your computer and use it in GitHub Desktop.
Save OtayNacef/345be3db0ef1bc8c6121fc1a5fe9e6b6 to your computer and use it in GitHub Desktop.
Javascript pagination that returns currentPage , totalItems , totalPages and items
export const formatPaginatedResponse = (rows: unknown[], count: number, page: string) => {
const itemsPerPage = Number(process.env.ITEMS_PER_PAGE);
const currentPage = Math.max(Number(page), 1) || 1;
return {
page: currentPage,
totalItems: count,
hasNextPage: itemsPerPage * displayPage < count,
totalPages: Math.max(Math.floor(count / itemsPerPage) + (count % itemsPerPage === 0 ? 0 : 1), 1),
items: rows,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment