WorkshopTasker/server/utils/database.ts

100 lines
2.4 KiB
TypeScript
Raw Normal View History

import { PrismaClient, Prisma } from "@prisma/client";
2023-05-11 06:03:22 +02:00
import { type pageData } from "./baaPageParsing";
2023-05-24 09:40:45 +02:00
type model = PrismaClient[Uncapitalize<Prisma.ModelName>];
2023-05-11 06:03:22 +02:00
function getBeforeParameters<T, A>(
pageData: pageData<false>,
fetchArgs: Prisma.Args<T, "findMany">,
) {
const _fetchArgs = Object.assign({}, fetchArgs);
return Object.assign(_fetchArgs, {
take: pageData.count,
orderBy: [
{ id: "desc" },
],
where: {
AND: [
{
id: {
_lt: pageData.id,
},
},
fetchArgs.where,
],
},
});
}
function getAfterParameters<T>(
pageData: pageData<false>,
fetchArgs: Prisma.Args<T, "findMany">,
) {
const _fetchArgs = Object.assign({}, fetchArgs);
return Object.assign(_fetchArgs, {
take: pageData.count,
orderBy: [
{ id: "desc" },
],
where: {
AND: [
{
id: {
_gt: pageData.id,
},
},
fetchArgs.where,
],
},
});
}
function getNullParameters<T>(
pageData: pageData<true>,
fetchArgs: Prisma.Args<T, "findMany">,
) {
const _fetchArgs = Object.assign({}, fetchArgs);
return Object.assign(_fetchArgs, {
take: pageData.count,
orderBy: [
{ id: "desc" },
],
});
}
export const database = new PrismaClient().$extends({
model: {
$allModels: {
findPaginated<T, A>(
this: T,
pageData: pageData,
fetchArgs: Prisma.Exact<A, Prisma.Args<T, "findMany">>,
): Promise<Prisma.Result<T, A, "findMany">> {
const context = Prisma.getExtensionContext(this) as any;
switch (pageData.type) {
case "before":
return context.findMany(getBeforeParameters(pageData, fetchArgs));
case "after":
return context.findMany(getAfterParameters(pageData, fetchArgs));
case "around":
return Promise.all([
context.findMany(getBeforeParameters({
type: "before",
id: pageData.id,
count: Math.ceil(pageData.count),
}, fetchArgs)),
context.findMany(getAfterParameters({
type: "after",
id: pageData.id,
count: Math.floor(pageData.count),
}, fetchArgs)),
]).then(rv => rv.flat()) as Promise<any>;
case null:
return context.findMany(getNullParameters(pageData, fetchArgs));
}
},
},
},
});