fix: use zod schema for parsing page query param

pull/9078/head
Agusti Fernandez Pardo 2022-07-08 20:15:25 +02:00
parent 76d0b0c1ee
commit 530752147e
1 changed files with 19 additions and 5 deletions

View File

@ -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();