我想在C#中尝试GraphQL

因为在Gjango中使用GraphQL库比我想象的要容易,所以我觉得这也可以在C#中实现。于是我试着运行了一段示例代码。
只需要做的是定义Schema并编写Query和Mutation,就能完成GraphQL API。

因为有一个使用C#进行GraphQL试验的示例代码,所以我参考它作为备忘录。

请参考下方链接。

通过各种调查研究得出的链接。

GraphQL .NET

今回使用するライブラリのドキュメントです。

サンプルコード

今回使用するサンプルコード。examples/src/AspNetCoreに配置されているプロジェクトを使用しました。

サンプルデータ

ドキュメントと同じスターウォーズのキャラクターがサンプルデータとして使われています。スターウォーズ見たことない人はこちらを参考に。

「GraphQL」徹底入門 ─ RESTとの比較、API・フロント双方の実装から学ぶ

GraphQLの用語の説明・実際に使用するときに生じる問題点など、とても参考になりました。

先试试看动一下

让我们克隆源代码并运行它.

# サンプルコードをクローンします
git clone https://github.com/graphql-dotnet/examples.git
# 使用するプロジェクトへ移動
cd examples\src\AspNetCore
# スクリプトを実行(中身はdotnet CLIのコマンドを実行してるだけ)
./run.sh
graphql_playground.png

执行突变 (zhí tū

mutation  {
  createHuman(human:{ name: "hoge_001", homePlanet: "hogehogeplanet"}) {
    name
    homePlanet
  }
}

执行查询

query {
  human(id:"1"){
    name
  }
}

结构

模式类型

在Schema中定义了Query和Mutation。

    public class StarWarsSchema : Schema
    {
        public StarWarsSchema(IServiceProvider provider)
            : base(provider)
        {
            Query = provider.GetRequiredService<StarWarsQuery>();
            Mutation = provider.GetRequiredService<StarWarsMutation>();
        }
    }

以下是在Query和Mutation中使用的类的示例。以下类的属性对应于Query和Mutation的字段名。

    public abstract class StarWarsCharacter
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string[] Friends { get; set; }
        public int[] AppearsIn { get; set; }
    }

    public class Human : StarWarsCharacter
    {
        public string HomePlanet { get; set; }
    }

    public class Droid : StarWarsCharacter
    {
        public string PrimaryFunction { get; set; }
    }

查询

在查询中编写用于获取数据的处理逻辑。

    public class StarWarsQuery : ObjectGraphType<object>
    {
        public StarWarsQuery(StarWarsData data)
        {
            // クエリあることを設定する
            Name = "Query";

            // heroというクエリを定義                  ↓LINQが書ける
            Field<CharacterInterface>("hero", resolve: context => data.GetDroidByIdAsync("3"));
         }
     }

突变

我会追着写的。

广告
将在 10 秒后关闭
bannerAds