Positional Arguments
What is it
Arguments in Graphql resolvers provide a way for other node/entity connections and sub-fields to retain context from the parent node/entity.
const resolvers = { Query: { user(parent, args, contextValue, info) { return users.find((user) => user.id === args.id); }, }, };
parent
The return value
of the resolver
for this field's parent
(previous resolver
in the resolver chain
).
At top-level fields without a parent
, this value is obtained from the rootValue
function passed to Apollo server's constructor.
args
An object that contains all GraphQL arguments
provided for this field.
# query query { user(id: "4") } # arg obj passed to user resolver args = { "id": "4" } # resolver const resolvers = { Query: { user(parent, args, contextValue, info) { return users.find((user) => user.id === args.id); # args.id = "4" }, }, };
contextValue
Object shared across all resolvers executing for a particular operation.
Use this to share per-operation state
.
- use this for auth information, dataloader instances, database connections, and anything else to track across resolvers.
When calling a service method on a resolver field, to keep the context
, you might have to pass the context
explicitly as another parameter.
Caveat
You cannot use context
to reference a value from another resolver as a general purpose cache.
When you store a value from another resolver into context and make a call via context.value
from another resolver, there is no guarantee that the context.value
will not be null.
- Long-running resolver function may not complete in time for another field to reference. Ideally every resolver should be separate from each other to avoid sharing state between each other and tightly coupling.
info
Information about the operation's execution state.
- field name, path to the field from the root, and etc.