#Overfetching problem
16 messages · Page 1 of 1 (latest)
yeah, overfetching can be a real pain, especially with rest
so since you’re using prisma, you can optimize your queries by selecting only the fields you actually need
and instead of pulling entire models, use prisma’s select or include options to fine-tune your queries
const user = await prisma.user.findUnique({
where: { id: userId },
select: { id: true, name: true, email: true }, // Only fetch required fields
});
if you’re dealing with nested relationships, include can help, but be mindful of how much data you’re pulling
you might also consider pagination and filtering at the query level to avoid unnecessary load
yes I have tried to test the prisma select function, but if for example that same findUserById method i want to use it in other places where i have different data to bring from my db it would not work, i have tried to make it generic but the problem with the types is a headache.
Do you think I over complicate it too much or for each type of select I have to make all specific method for that case?
yeah, i got what you are saying, just the type issues with making a flexible findUserById function in prisma can be annoying
so there are 3 option to fix it, i think
first, y ou can pass the select object as a parameter so you control what fields on a case-by-case basis
async function findUserById(userId: string, selectFields: Prisma.UserSelect) {
return prisma.user.findUnique({
where: { id: userId },
select: selectFields,
});
}
// Example usage:
const user = await findUserById(userId, { id: true, name: true });
const userWithEmail = await findUserById(userId, { id: true, name: true, email: true });
this way, you dont hardcode what gets getched, and typescript should infer the correct return type
and second, you can use different specific funcions
just if the dynamic approach is getting too messy, it's totally fine to have separate functions like findUserBasicInfo(userId), findUserWithEmail(userId)
so it keeps things clean and avoids type headeraches
last is to use type helper, just if typescript is being difficult, lol
if typescript is giving you trouble, you can create a helper type to ensure selectFields always matches the prisma schema, lol...
async function findUserById<T extends Prisma.UserSelect>(
userId: string,
selectFields: T
): Promise<Prisma.UserGetPayload<{ select: T }>> {
return prisma.user.findUnique({
where: { id: userId },
select: selectFields,
});
}
this keeps type safety while allowing flexibility
anyway, it depends on how complex your queries get~~~~