cal.pub0.org/lib/helpers/withPagination.ts

26 lines
520 B
TypeScript
Raw Normal View History

2022-07-05 18:12:14 +00:00
import { NextMiddleware } from "next-api-middleware";
import z from "zod";
2022-07-05 18:12:14 +00:00
const withPage = z.object({
2022-07-08 18:19:51 +00:00
page: z
.string()
.optional()
.default("1")
.transform((n) => parseInt(n)),
take: z
.string()
.optional()
.default("10")
.transform((n) => parseInt(n)),
});
export const withPagination: NextMiddleware = async (req, _, next) => {
2022-07-08 18:19:51 +00:00
const { page, take } = withPage.parse(req.query);
const skip = page * take || 0;
2022-07-05 18:12:14 +00:00
req.pagination = {
take,
skip,
2022-07-05 18:12:14 +00:00
};
await next();
};