From 530752147e560bc6ca87d3dfa94b41cd546c843c Mon Sep 17 00:00:00 2001 From: Agusti Fernandez Pardo Date: Fri, 8 Jul 2022 20:15:25 +0200 Subject: [PATCH] fix: use zod schema for parsing page query param --- lib/helpers/withPagination.ts | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/lib/helpers/withPagination.ts b/lib/helpers/withPagination.ts index 6d76c680f1..2bcd219b33 100644 --- a/lib/helpers/withPagination.ts +++ b/lib/helpers/withPagination.ts @@ -1,11 +1,25 @@ import { NextMiddleware } from "next-api-middleware"; +import z from "zod"; -export const withPagination: NextMiddleware = async (req, res, next) => { - const { page } = req.query; - const pageNumber = parseInt(page as string); - const skip = pageNumber * 10; +const withPage = z.object({ + pageNumber: z + .string() + .min(1) + .default("1") + .transform((n) => parseInt(n)), + take: z + .string() + .min(10) + .max(100) + .default("10") + .transform((n) => parseInt(n)), +}); + +export const withPagination: NextMiddleware = async (req, _, next) => { + const { pageNumber, take } = withPage.parse(req.query); + const skip = pageNumber * take; req.pagination = { - take: 10, + take: take || 10, skip: skip || 0, }; await next();