I want to modify data from a prisma query before u...
# orm-help
g
I want to modify data from a prisma query before users receive the data through the various
prisma.modelName.queryName
methods - but after the query successfully complets. As a contrived example, let’s say I have a model like this:
Copy code
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:
Copy code
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 docs
d
Why do you want to do this in Prisma? This seems like a processing step to be done after, by just setting:
Copy code
bob.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:
Copy code
const res = await next(params);
return {
    ...res,
    first_name: `${res.gender}. ${res.first_name}`
}
j
In the middleware, you just do it after calling
next
which executes the query.
So where it says "see results here" you would do your logic.
So similar to how @David describes it indeed 👍
g
Thank you both!