Giorgio Delgado
07/05/2021, 4:41 PMprisma.modelName.queryName methods - but after the query successfully complets.
As a contrived example, let’s say I have a model like this:
model Person {
id @id @default(cuid())
first_name String
gender Gender
}
Now what if I want to modify first_name after fetching it from the database to include Mr or Ms.
so that if i do:
const bob = await prisma.person.findFirst({
where: { id: someCuid }
})
Then bob.first_name should say Mr. bob or something like that.
I know that Prisma has middleware using prisma.$use but I don’t quite understand how i’d go about doing this since this is a post-query modification … as opposed to a pre-query modification that I see examples of in the docsDavid
07/05/2021, 4:52 PMbob.first_name = `${bob.gender}. ${bob.first_name}`;
This seems like a more straighforward solution, especially if you're using a common interface (i.e. a UserService) to access the model.
However, i've not actually done this but afaik, you do it in the same middleware. Anything you put before await next(params); happens before the query, and any code after that is once the query has returned.
So you should be able to do something like this in your middleware:
const res = await next(params);
return {
...res,
first_name: `${res.gender}. ${res.first_name}`
}janpio
next which executes the query.janpio
janpio
janpio
Giorgio Delgado
07/05/2021, 5:38 PM