LoginSignup
4
7

C#でGraphQL(なぜホットチョコレート?!)

Last updated at Posted at 2023-10-25

最近、C#界隈でもGrphQL案件が増えてきたので調査してみました。

GraphQLサーバ

ふざけた名前のホットチョコレート(Hot Chocolate)?!を使ってみたいと思います。

Microsoftも紹介しているのできっと大丈夫でしょう!

準備

1. VisualStudio2022で空のASP.NETCoreプロジェクトを作成作成します。
image.png

image.png
2. NugetでHotChocolate.AspNetCoreを追加します。
image.png

今回テストしたスキーマ

今回は以下のスキーマを定義したいと思います。

  • Authorとそれに紐づくBookを想定(1対多)
  • 今回はQueryだけ
type Query {
    authors: [Author]
    books: [Book]
}
type Author {
    id: Int!
    name: String!
    books: [Books]
}
type Book {
    id: Int!
    title: String!
    author: Author
}  

コード

準備したプロジェクトのProgram.csを以下で上書きしてください。
概要は以下です。

  • データはRepositoryクラス(シングルトン)内で生成。
  • スキーマはAuthorとBookの2種類。
var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddSingleton<Repository>()
    .AddGraphQLServer()
    .AddQueryType<Query>();
var app = builder.Build();

app.MapGraphQL();

app.Run();

public class Query
{
    public IEnumerable<Author> Authors([Service] Repository repository)
    {
        return repository.GetAuthors();
    }
    public IEnumerable<Book> Books([Service] Repository repository)
    {
        return repository.GetBooks();
    }
}
public class Author
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Book> Books { get; set; }
}
public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public Author Author { get; set; }
}
public class Repository
{
    private readonly List<Author> _authors;
    public Repository()
    {
        //データ登録
        _authors = new List<Author>();

        //川端康成
        var auther = new Author
        {
            Id = 1, Name = "川端康成",
        };
        auther.Books = new List<Book>
        {
            new Book { Id = 11, Title = "雪国", Author = auther},
            new Book { Id = 12, Title = "伊豆の踊り子", Author = auther}
        };
        _authors.Add(auther);

        //夏目漱石
        auther = new Author
        {
            Id = 2, Name = "夏目漱石",
        };
        auther.Books = new List<Book>
        {
            new Book { Id = 21, Title = "坊ちゃん", Author = auther},
            new Book { Id = 22, Title = "三四郎", Author = auther}
        };
        _authors.Add(auther);
    }
    public IEnumerable<Author> GetAuthors()
    {
        return _authors;
    }
    public IEnumerable<Book> GetBooks()
    {
        return _authors.SelectMany(x => x.Books);
    }
}

テスト

デバッガで起動して以下を開いてください。
  http://localhost:ポート番号/graphql/
専用の画面が出るのでQueryを書いてRunをクリックします。

image.png

試しに他のQueryも書いてみます。
image.png

感想

基本的な所は、結構簡単に動きました。
ホットチョコレートちゃんとしてます!
マニュアルも充実しているようです。
https://chillicream.com/docs/hotchocolate/v13/fetching-data/filtering
ページネーションやフィルタリングのやり方も機会があればトライしてみたいと思います。

4
7
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
4
7