I'm the new guy in the GraphQL world and trying to find a way to have multiple Query types or how to split the Query type into multiple files.. I use Hot Chocolate for Asp.Net Core, and everything looks good and works. But what if I need to combine few queries in one GraphQL API? Some really unrelated stuff, f.e. DogsQuery and CarsQuery.
In Asp.Net, I write similar to:
public void ConfigureServices(IServiceCollection services)
{
services
.AddGraphQLServer()
//.AddQueryType<DogsQuery>()
.AddQueryType<CarsQuery>();
}
It works fine if I use only one Query class simultaneously (Dogs or Cars). But how to use both? I've searched a lot but can't find the answer.
You cannot have multiple Query/Mutation/Subscription types in graphql, but you can split the types to multiple files in HotChocolate.
You can use the [ExtendObjectType(Name = "Query")]
attribute above both your query types. This works for the Subscriptions ([ExtendObjectType(Name = "Subscription")]
) and Mutations ([ExtendObjectType(Name = "Mutation")]
) the same way.
This attribute is used for merging any two graphql types in the same HotChocolate server. The name value must be the name of the GraphQl type you want to merge your C# class into. In this case it is Query
.
After doing that, you can add the types to your server like this:
public void ConfigureServices(IServiceCollection services)
{
services
.AddGraphQLServer()
.AddQueryType(d => d.Name("Query"))
.AddTypeExtension<DogsQuery>()
.AddTypeExtension<CarsQuery>();
}
You can find this and many more useful things in the workshop example on Github: https://github.com/ChilliCream/graphql-workshop