[Hydration] Is there any helper that collects the requested root fields and returns them as an array?
See original GitHub issueI have a resolver that fetch a list of authors. Author’s entity have many columns in database such as id
, name
, role
, isActive
, createdAt
, updatedAt
etc. However my GraphQL API exposes only three fields: id
, name
, role
.
descriptor.Field(t => t.Authors)
.Type<NonNullType<ListType<AuthorType>>>()
.Resolver(ctx =>
{
<repository fetching stuff>
}
}
To optimize the speed of the resolver, I want to request from the repository only the necessary columns, and not all in a row. Actually, the question arose: How can I get a list of requested fields from the ctx
?
I know that in context there is a property ctx.FieldSelection.SelectionSet
, and I can just select each item’s name with Linq. But fragments can also act as fields. And then you need to read the whole scheme in search of this fragment and get a list of fields there.
Does the HotChocolate have any helper to solve this problem?
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (5 by maintainers)
Top GitHub Comments
@acelot your example will work when
ctx.Field.Type
is an object type. If you have a union or an interface you can ask for all possible typesctx.Schema.GetPossibleTypes(cox.Field.Type.NamedType())
.With that you can ask for the fields of each case.
If you want to walk the graph further you can pass in any selectionSet to
CollectFields
and the type context for that selection set.If you want to generalize your solution you can put that in a middleware and use it on multiple fields…
https://hotchocolate.io/docs/middleware#field-middleware
So the easiest way to do that is with our
IResolverContext.CollectFields
fields. This will pull in the fields that have to be resolved in the next level. There are two overloads that allow you to walk the graph and look at all the levels in all possible combinations. This will let you focus on what fields to fetch.CollectFields
will compute@skip
and@include
and also resolve all fragments.