From 6cec8620cb8f6a8a797088566da7ec0e3e0001be Mon Sep 17 00:00:00 2001 From: Leo Giovanetti Date: Wed, 18 Jan 2023 16:49:31 -0300 Subject: [PATCH] Pagination issue fixed, total added (#227) Fixes #217. --- lib/helpers/withPagination.ts | 2 +- pages/api/users/_get.ts | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/helpers/withPagination.ts b/lib/helpers/withPagination.ts index 32ff4a7289..8a78b03c2b 100644 --- a/lib/helpers/withPagination.ts +++ b/lib/helpers/withPagination.ts @@ -16,7 +16,7 @@ const withPage = z.object({ export const withPagination: NextMiddleware = async (req, _, next) => { const { page, take } = withPage.parse(req.query); - const skip = page * take || 0; + const skip = (page - 1) * take; req.pagination = { take, skip, diff --git a/pages/api/users/_get.ts b/pages/api/users/_get.ts index 6e9b9c1c2b..3ccfdb6ca0 100644 --- a/pages/api/users/_get.ts +++ b/pages/api/users/_get.ts @@ -39,9 +39,12 @@ async function getHandler(req: NextApiRequest) { const where: Prisma.UserWhereInput = {}; // If user is not ADMIN, return only his data. if (!isAdmin) where.id = userId; - const data = await prisma.user.findMany({ where, take, skip }); + const [total, data] = await prisma.$transaction([ + prisma.user.count(), + prisma.user.findMany({ where, take, skip }), + ]); const users = schemaUsersReadPublic.parse(data); - return { users }; + return { users, total }; } export default withMiddleware("pagination")(defaultResponder(getHandler));