Created
February 26, 2024 10:55
-
-
Save Alex4386/c3689fa8bcc7b4a1ac275b4efe81181a to your computer and use it in GitHub Desktop.
Prisma Pagination Stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PrismaClient } from '@prisma/client'; | |
import { FastifyRequest } from 'fastify'; | |
import { getPaginationDataFromRequest } from './mysql'; | |
type PrismaQueryTargetsRaw = Omit<PrismaClient, `$${string}`>; | |
type PrismaQueryTargets = { | |
[K in keyof PrismaQueryTargetsRaw as K extends symbol ? never : K]: PrismaQueryTargetsRaw[K]; | |
}; | |
type PrismaQueryTarget = PrismaQueryTargets[keyof PrismaQueryTargets]; | |
export function getPaginationDataFromRequest(req: FastifyRequest): { page: number; size: number } { | |
let { page, size } = req.query as any; | |
if (/^[0-9]+$/.test(page)) page = parseInt(page); | |
else page = 1; | |
if (/^[0-9]+$/.test(size)) size = parseInt(size); | |
else size = 50; | |
return { page, size }; | |
} | |
export async function returnPaginationInfo<T extends PrismaQueryTarget>( | |
req: FastifyRequest, | |
obj: T, | |
query: Parameters<T['findMany']>[0], | |
): Promise<{ | |
data: Awaited<ReturnType<T['findMany']>>; | |
pagination: { | |
page: number; | |
size: number; | |
maxPage: number; | |
counts: number; | |
}; | |
}> { | |
const { page, size } = getPaginationDataFromRequest(req); | |
const counts = await (obj as any).count(query); | |
return { | |
data: await (obj as any).findMany({ | |
...query, | |
skip: (Math.max(page, 1) - 1) * size, | |
take: size, | |
}), | |
pagination: { | |
page, | |
size, | |
maxPage: Math.max(1, Math.ceil(counts / size)), | |
counts, | |
}, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment