I wrote some resolvers following the default GraphQL resolver function' signature that can optionally accept four positional arguments: fieldName: (parent, args, context, info) => data;. But the parent argument is completely absent in child resolvers:
...
const resolvers = [
{
Query: {
prop1: (parent, args, context, info) => ({
childProp1: (args, context, info) => 'Child Property 1',
childProp2: (args, context, info) => 'Child Property 2',
}),
}
}
]
const server = new ApolloServer(
{
typeDefs,
resolvers,
}
);
Unfortunately, I did not find any reference about child resolvers function' arguments in the GraphQL documentation. So I wonder how would be the right way to get the parent object in child resolvers.
Resolvers that are methods of the object whose fields are accessed do not need a parent argument, they are called as methods with their this argument pointing to the object.
When you have
class Value {
constructor(x) {
this.property = x;
}
methodChild() {
return this.property;
}
}
const resolvers = {
Query: {
prop1: (parent, args, context, info) => new Value('Child Property X'),
},
Value: {
resolverChild: (parent, args, context, info) => parent.property;
}
}
then you can declare a
type Value {
property: String; # directly accessed as value property
methodChild: String; # directly invoked as method
resolverChild: String; # separately resolved
}
and all three fields will result in the same value.