GraphQL 既是一種用於 API 的查詢語言也是一個知足你數據查詢的運行時。GraphQL 對你的 API 中的數據提供了一套易於理解的完整描述,使得客戶端可以準確地得到它須要的數據,並且沒有任何冗餘,也讓 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-First public 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-First public 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-First public 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方法,不過看來也只有這樣一個數據了。asp.net