I have a query like:
user(id: 1) {
company {
userProfile
}
}
The company resolver looks something like:
class CompanyResolver
def call(user_obj, args, ctx)
return user_obj.company
end
end
Because it's a child of the :user field directly, it can access the resolved user (which is good, but...)
The userProfile resolver also needs the user model.
class UserProfileResolver
def call(company_obj, args, ctx)
return company_obj.some_method(user.id).profile
# How do I access the resolved user in the above line?
end
end
obj in this second resolver is the company, which won't have a reference to the user. ctx.ast_node seems to have no way to walk up to the parent (there's no .parent method) so I'm not sure how to use a higher resolved obj in a lower resolver?
TL;DR:
parent_ctx = ctx.parent
parent_obj = parent_ctx.object
# => company
ctx is part of the response tree, so you can use it to backtrack to the previous response node and get the object from it. It's an instance of GraphQL::Query::FieldResolutionContext.
@rmosolgo How can one access the parent object in the new class-based API?
@rmosolgo Never mind, found my answer in https://github.com/rmosolgo/graphql-ruby/issues/881#issuecomment-383113993, thanks!
1.9.17 will introduce "scoped" context, a part of context which is added _for child fields_ only #2634
You could ctx.scoped_set(:found_user, user), and then ctx[:found_user] would return that user, but _only for subselections_ of the user(id: 1) field (including "grandchildren")!
Awesome, thank you!
@rmosolgo Scoped context is marked as @api private. Generally, the best practice is to shy away from using private APIs because new versions are more likely to introduce breaking changes. How stable is this feature? Are there plans to make scoped context part of the public API?
Sorry, it really shouldn't be marked @api private. It's 100% stable (added by Shopify and I think they depend on it, also 100% generally useful). If you don't mind, a PR to remove that tag (or just a link to where you saw it) would be great. Also so some docs for graphql-ruby.org, maybe one of these days 馃槄 !
Most helpful comment
TL;DR:
ctxis part of the response tree, so you can use it to backtrack to the previous response node and get the object from it. It's an instance ofGraphQL::Query::FieldResolutionContext.