'How to get requested GraphQL fields in C#?
I'm working on a GraphQL -> SQL parser that includes some joins, so it makes a performance difference whether a certain field is requested. Is there a way to find that out?
I'm learning about object types, so I think it might have something to do with setting a resolver on it. But a resolver works at the level of the field that's being requested independently of other things. Whereas I'm trying to figure out on the top-most Query level which fields have been requested in the GraphQL query. That will shape the SQL query.
public class QueryType : ObjectType<Query>
{
protected override void Configure(IObjectTypeDescriptor<Query> descriptor)
{
descriptor
.Field(f => f.GetACUMonthlySummary(default!, default!, default!, default!, default!, default!))
.Type<ListType<ACUMonthlySummaryType>>();
}
}
I saw related questions for js, but didn't find any examples specifically in C# and HotChocolate, which is what we're using.
Solution 1:[1]
Say for example(A simple one) you have a class called employee and it has FirstName
and LastName
properties. You may want want the GraphQL endpoint to expose a FullName
field for the employee that will internally concatenate the first and last name
. Note that FirstName and LastName values exist as columns of the Employee database table but the FullName
field will be derived.
public class EmployeeType : ObjectType<Employee> {
protected override void Configure(IObjectTypeDescriptor<Employee> descriptor) {
descriptor.Field(@"FullName")
.Type<StringType>()
.ResolveWith<Resolvers>( p => p.GetFullName(default!, default!) )
.UseDbContext<AppDbContext>()
.Description(@"Full name of the employee");
}
private class Resolvers {
public string GetFullName([Parent] Employee e, [ScopedService] AppDbContext context) {
return e.FirstName + " " + e.LastName;
}
}
}
I'm pretty sure you'd have to annotate the Employee using the ParentAttribute.
Solution 2:[2]
I'm not sure if this is recommended, so I appreciate feedback, but I found the following way to list all selected nodes:
- Inject
IResolverContext context
(using HotChocolate.Resolvers) as one of the parameters in the query. context.Selection.SyntaxNode.SelectionSet.Selections
gives anIEnumerable<ISelectionNode>
. That contains exactly the fields the user has selected.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | David Kariuki |
Solution 2 | Oleksiy |