2021-07-06 16:10:22 +00:00
|
|
|
import { PrismaClient } from "@prisma/client";
|
2021-03-22 13:48:48 +00:00
|
|
|
|
2021-04-11 17:12:18 +00:00
|
|
|
let prisma: PrismaClient;
|
2021-07-06 16:10:22 +00:00
|
|
|
const globalAny: any = global;
|
2021-03-22 13:48:48 +00:00
|
|
|
|
2021-07-06 16:10:22 +00:00
|
|
|
if (process.env.NODE_ENV === "production") {
|
2021-04-11 17:12:18 +00:00
|
|
|
prisma = new PrismaClient();
|
2021-03-22 13:48:48 +00:00
|
|
|
} else {
|
2021-04-29 13:47:01 +00:00
|
|
|
if (!globalAny.prisma) {
|
|
|
|
globalAny.prisma = new PrismaClient();
|
2021-03-22 13:48:48 +00:00
|
|
|
}
|
2021-04-29 13:47:01 +00:00
|
|
|
prisma = globalAny.prisma;
|
2021-03-22 13:48:48 +00:00
|
|
|
}
|
|
|
|
|
2021-07-06 18:20:25 +00:00
|
|
|
const pluck = (select: Record<string, boolean>, attr: string) => {
|
|
|
|
const parts = attr.split(".");
|
|
|
|
const alwaysAttr = parts[0];
|
|
|
|
const pluckedValue =
|
|
|
|
parts.length > 1
|
|
|
|
? {
|
|
|
|
select: pluck(select[alwaysAttr] ? select[alwaysAttr].select : {}, parts.slice(1).join(".")),
|
|
|
|
}
|
|
|
|
: true;
|
|
|
|
return {
|
|
|
|
...select,
|
|
|
|
[alwaysAttr]: pluckedValue,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2021-07-06 16:10:22 +00:00
|
|
|
const whereAndSelect = (modelQuery, criteria: Record<string, unknown>, pluckedAttributes: string[]) =>
|
|
|
|
modelQuery({
|
|
|
|
where: criteria,
|
2021-07-06 18:20:25 +00:00
|
|
|
select: pluckedAttributes.reduce(pluck, {}),
|
2021-07-06 16:10:22 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
export { whereAndSelect };
|
|
|
|
|
|
|
|
export default prisma;
|