WorkshopTasker/server/utils/database.ts
Wroclaw 8bfc059b66
All checks were successful
Build dev / build (push) Successful in 1m18s
server/utils/database: ensure that database engines exists.
2023-12-20 04:01:04 +01:00

102 lines
2.5 KiB
TypeScript

import { PrismaClient, Prisma } from "@prisma/client";
import * as PrismaEngines from "@prisma/engines";
import { type pageData } from "./baaPageParsing";
type model = PrismaClient[Uncapitalize<Prisma.ModelName>];
PrismaEngines.ensureBinariesExist();
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));
}
},
},
},
});