I am working with a project that uses graphQL. I understand that graphQL apis are supposed to prevent overfetching (and underfetching) of data but I do not understand how this is supposed to work in real life.
Say I have a query to get employee data like this:
const getEmployeesQuery = `
query GetEmployees($aliases: [String]) {
getEmployees(aliases: $aliases) {
personId
username
fullName
businessTitle
email
trainings
location {
id
name
buildingCode
timezone
city
country
}
}
}
`;
export default getEmployeesQuery;
When this query is executed, our backend will get all this data from a variety of sources. However suppose that the request does not include trainings in the request. What I don't understand is how can the backed identify that this field is not there and then NOT make the operations to get that data?
Is the graphQL backend supposed to parse through this string to determine what the user requested at every level? That seems unrealistic.
Ideally if I don't include trainings (or any particular field) then the backend should be optimized to not retrieve that data, right? The query I posted here is relatively simple but we have some that are extremely nested.
The frontend will only end up receiving data included in the request but shouldn't we be preventing the backend from getting data not included in the request body? That is what I don't understand.
You're correct; one of the main benefits of
GraphQLis that it doesn't over-fetch.From
clienttoserver, this is easy to prevent. Request the fields you want, and theclientwill receive them from theserver. So just removetrainingsfrom your Client-side request. However, that doesn't preventGraphQLfrom hitting yourdatabasefor every field in your request, includingtrainings.What you need is to pass the
infodata at theResolverlevel. I am currently usingNestjswithGraphQL&knexso my implementation looks like this:Focus on
InfoYou'll now have access to the requested fields in your service and can now use them something like this:
Hope this helps!