GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。
——出自 https://graphql.cn
前面几篇博文介绍了GraphQL在asp.net core框架下的实例,初步了解到Hot Chocolate的功能,不如从这篇开始,细致的过一下Hot Chocoklate,看看.net下这个GrpahQL框架究竟做了点什么,我们又能做点什么。
首先使用HotChocolate有两种姿势,代码姿势(code-first)和脚手架姿势(schema-first),那长什么样呢?实例送上:
using HotChocolate;
using HotChocolate.Execution;
using HotChocolate.Types;
using System;namespace GraphQLBase001
{class Program{static void Main(string[] args){var schemaString = @"type Query {hello: String}";Console.WriteLine("Schema-First");SchemaFirst.Run(schemaString);Console.WriteLine("Schema-First");CodeFirst.Run(schemaString);Console.WriteLine("PurCode-First");PureCodeFirst.Run();C.Run(schemaString);D.Run(schemaString);E.Run();}}#region Schema-Firstpublic class SchemaFirst{public static void Run(string schemaString){var schema = SchemaBuilder.New().AddDocumentFromString(schemaString).AddResolver("Query", "hello", () => "world").Create();var executor = schema.MakeExecutable();Console.WriteLine(executor.Execute("{ hello }").ToJson());}}#endregion#region Code-Firstpublic class CodeFirst{public static void Run(string schemaString){var schema = SchemaBuilder.New().AddDocumentFromString(schemaString).BindComplexType<Query>().Create();var executor = schema.MakeExecutable();Console.WriteLine(executor.Execute("{ hello }").ToJson());}public class Query{/// <summary>/// 目测这里只对Hello或GetHello免疫/// </summary>/// <returns></returns>public string Hello() => "world";}}#endregion#region PureCode-Firstpublic class PureCodeFirst{public static void Run(){var schema = SchemaBuilder.New() .AddQueryType<Query>().Create();var executor = schema.MakeExecutable();Console.WriteLine(executor.Execute("{ hello }").ToJson());}public class Query{/// <summary>/// 目测这里只对Hello或GetHello免疫/// </summary>/// <returns></returns>public string Hello() => "world";}}#endregion
}
通过上面实例,这两种不同点在于Query是定义了一个类来实现,还是通过一个约定字符串来实现,本质上都是一个方法(也可以是属性要一个字符串的返回值)。如果你注意到了PureCode-First,这只是一个变种,不过这个看起来对一个C#程序来说情怀实足。
其中不管那种方式,执行api的方式始终不变"{hello}",这里我们实际上调用的是hello方法,不过看来也只有这样一个数据了。