LoginSignup
2
1

More than 3 years have passed since last update.

C#でGraphQLを試したい

Last updated at Posted at 2021-03-23

GjangoでGraphQLのライブラリを使ったところ思ってたよりも簡単に書けたので、これはC#でも行けるのでは?と思い試しにサンプルコードを動かすに至りました。
やることは簡単、Schemaを定義してQueryとMutationを書けばGraphQL APIの完成です。

C#でGraphQLを試すサンプルコードがあったのでそれを参考にして備忘録です。

参考リンク

色々調べた結果たどり着いたリンクたち。

とりあえず動かしてみる

ソースコードをクローンして動かしてみましょう

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

実行したらhttp://localhost:3000/ui/playgroundへアクセスします。
graphql_playground.png
上のような画面が表示されるかと思うのでこれでGraphQLを試す環境が整いました。
以下のコマンドでサンプルコードのテストができます。

Mutationを実行

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

Queryを実行

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

Schema

Schema Type

SchemaにはQueryとMutationを定義します。

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

またQueryとMutationで使うクラスは以下のようになります。
以下のクラスのプロパティがQueryとMutaitionのフィールド名と対応します。

    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; }
    }

Query

Queryにはデータを取得するための処理を書きます。

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

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

Mutation

追々書きます。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1