GraphQL fields are never resolved unless they are explicitly requested.
Let's look at a slightly more complicated example. Let's say we have this schema:
type Query {
getUser: User
}
type User {
firstName: String
lastName: String
fullName: String
}
And our resolvers look like this:
const resolvers = {
Query: {
getUser: () => ({ firstName: 'Susan', lastName: 'Martinez' }),
},
User: {
fullName: (user) => `${user.first_name,} ${user.last_name,}`,
},
}
We return a user object in our getUser
resolver. We rely on the default resolver behavior for the firstName
and lastName
fields, but provide a custom resolver for fullName
. If we make this query:
query {
getUser {
firstName
}
}
only two resolvers are called -- the one for getUser
and the one for firstName
. However, this query
query {
getUser {
firstName
fullName
}
}
will also cause the fullName
resolver to be called. Each resolver has access to whatever value the parent field resolved to. So if determining the fullName
is expensive, you can move the logic for evaluating that value into the field's resolver.
On the other hand, if you just need to know which child fields were requested, there's already an answer for that.