GraphQL:来来来,Union
作者:互联网
Union就是把不相干的一些数据实体,合并起来,一起供外部查询。不用像webapi,完成查询不同的数据,需要多次请求。一次请求,获取多样数据,减少请求次数,这也是GraphQL的优势之一。怎么弄,来来来,代码看过来:
using HotChocolate; using HotChocolate.Execution; using HotChocolate.Types; using System; namespace GraphQLBase006 { class Program { static void Main(string[] args) { UnionDemo.Run(); } } public class UnionDemo { public static void Run() { var schema = SchemaBuilder.New() .AddQueryType<Query>() .AddType<Car>() .AddType<Cabbage>() .AddType<Earth>() .AddProjections() .Create(); var executor = schema.MakeExecutable(); Console.WriteLine(executor.Execute(@" { formats { __typename, ... on Car{ brand, price }, ... on Cabbage{ name, nutrition } ... on Earth{ diameter } } }").ToJson()); } } public class Query { public IUnion[] GetFormats() { return new IUnion[] { new Car{ Brand="Benz", Price=1000000 }, new Cabbage{ Name="灰子白", Nutrition="纤维" }, new Earth{ Diameter=12742 } }; } } [UnionType("Unio")] public interface IUnion { } public class Car : IUnion { public string Brand { get; set; } public decimal Price { get; set; } } public class Cabbage : IUnion { public string Name { get; set; } public string Nutrition { get; set; } } public class Earth : IUnion { public double Diameter { get; set; } } }
案例中就是把不相干的Car,Cabbage,Earth,通过继承一个空接口合并起来,供外部访问,通过自定义查询接口语句,达到灵活取想要的数据,比如一些数据字典的查询就很有用,不相干的一些配置,同时获取到,以备后用。
结果:
{ "data": { "formats": [ { "__typename": "Car", "brand": "Benz", "price": 1000000 }, { "__typename": "Cabbage", "name": "\u7070\u5B50\u767D", "nutrition": "\u7EA4\u7EF4" }, { "__typename": "Earth", "diameter": 12742 } ] } }
想要更快更方便的了解相关知识,可以关注微信公众号
标签:set,get,Union,Car,class,IUnion,GraphQL,来来来,public 来源: https://www.cnblogs.com/axzxs2001/p/15861448.html