In Prisma, I know we can filter with where
the records that we include
in a certain .findMany
request as specified in the doc:
const result = await prisma.user.findMany({
// ...
include: {
posts: {
where: {
published: true,
},
},
},
})
I would like to do the same, but in a computed field. I created a computed field for a batch
model that returns the amount of disposals
done for a certain batch
( batch 1–N disposals ) in the past 7 days.
I would like the following code to work:
type BatchExtended = {
id?: string;
startDate?: Date;
endDate?: Date;
disposals?: Disposal[];
};
prisma = new PrismaClient().$extends({
result: {
batch: {
lastWeekDisposals: {
include: {
disposals: {
where: {
createdAt: {
gte: add(new Date(), { weeks: -1 }),
lte: new Date(),
},
}
}
},
compute(batch: BatchExtended) {
return batch.disposals.length;
},
},
},
},
});
Unfortunately, despite the fact the above code doesn’t break, it doesn’t filter the disposals either and return all the disposal records, not just the past 7 days ones.
(note: in the code add
is from date-fns
).
The workaround code I have is the following. It works perfectly, but I expect its performance to be quite bad vs filtering within the prisma query:
prisma = new PrismaClient().$extends({
result: {
batch: {
lastWeekDisposals: {
include: {
disposals: true,
},
compute(batch: BatchExtended) {
return batch.disposals.filter(
(disp) =>
disp.createdAt >= add(new Date(), { weeks: -1 }) &&
disp.createdAt < new Date(),
).length;
},
},
},
},
});
Do you have a more elegant and better performance solution? Or a different approach to that problem?