GraphQL:从头开始
生活随笔
收集整理的這篇文章主要介紹了
GraphQL:从头开始
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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方法,不過看來也只有這樣一個數據了。
總結
以上是生活随笔為你收集整理的GraphQL:从头开始的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对 精致码农大佬 说的 Task.Run
- 下一篇: Kubernetes 1.20 发布:妙