在Hot Chocolate中,可以使用Union类型将多个类型合并到一个GraphQL类型中。这可以避免在一个类中表达太多的查询类型和突变。
以下示例演示如何使用Union类型将两个查询类型合并到一个GraphQL类型中:
using HotChocolate.Types;
public class QueryTypeA : ObjectType
{
protected override void Configure(IObjectTypeDescriptor descriptor)
{
descriptor.Name("QueryTypeA");
descriptor.Field(x => x.GetSomeData())
.Type();
}
}
public class QueryTypeB : ObjectType
{
protected override void Configure(IObjectTypeDescriptor descriptor)
{
descriptor.Name("QueryTypeB");
descriptor.Field(x => x.GetSomeOtherData())
.Type();
}
}
public class MultiQueryType : UnionType
{
protected override void Configure(IUnionTypeDescriptor descriptor)
{
descriptor.Name("MultiQueryType");
descriptor.Type();
descriptor.Type();
}
}
然后,在GraphQL API中可以像这样调用MultiQueryType:
query {
multiQuery {
... on QueryTypeA {
someData
}
... on QueryTypeB {
someOtherData
}
}
}
这将返回一个包含两个查询类型的MultiQueryType,并允许客户端查询它们的字段。