Prisma Client: `@map` on the query level
See original GitHub issueProblem
Hey! Would love it if the query builder API introduces a way to @map
on the query level. Per example change an id
field on the response object to be databaseId
but only on a single query. It’s possible via a raw query using as
but it would be nicer to do so on the query level. I think this would hugely increase performance on some cases when you have to loop on a findMany
response to change the name of certain fields.
Suggested solution
Take a select query:
const users = prisma.user.findMany({ take: 10 })
which is the equivalent to
SELECT `main`.`User`.`id`, `main`.`User`.`createdAt`, `main`.`User`.`updatedAt`,
`main`.`User`.`email`, `main`.`User`.`name` FROM `main`.`User` LIMIT 10
To map only for this specific query you’d have to
const newUsers = users.map(x => ({...x, databaseId: x.id, id: undefined }))
which can be done with sql via the as
operator like so (which is much much faster and scales very well):
SELECT `main`.`User`.`id` as databaseId, `main`.`User`.`createdAt`, `main`.`User`.`updatedAt`,
`main`.`User`.`email`, `main`.`User`.`name` FROM `main`.`User` LIMIT 10
Suggested API:
const users = prisma.user.findMany({ take: 10, map: { id: "databaseId" } })
Alternatives
Maybe not the keyword map
but something else to not confuse people?
Also with the suggested API I didn’t really give it much thought on how would it be properly typed but I am pretty sure it’s possible, either way that would be I guess one of the challenges.
Additional context
Issue Analytics
- State:
- Created 2 years ago
- Reactions:13
- Comments:5 (2 by maintainers)
Top GitHub Comments
Okay so here is what I was able to come up with (with a help from a friend of mine and a kind stranger in typescript’s discord)
Playground Link
Also this issue was helpful: https://github.com/microsoft/TypeScript/issues/30680
Limitations
databaseId
in our example) won’t change the dbOutput property name, for some reason typescript couldn’t pick that up ;/@map
will make all the queries returndatabaseId
instead ofid
, and will also change the property name for other methods (input and output), on the other hand, what I am proposing works basically for a specific single query and only for the returned data (not the input data).Motivation would be to give people more control on the shape of the returned data, in my case I want this so I can make the
id
adatabaseId
on certain parts of my app but not on all parts of the app