GraphQL Rubyのドキュメントを読む
https://scrapbox.io/files/64daaea7e24f47001bc35f41.png
canvaから拝借
トップ
gem installし
スキーマ定義し
クエリを書こう
code: ruby
# app/controllers/graphql_controller.rb
result = MySchema.execute(
context: { current_user: current_user },
)
render json: result
そもそもだけど、こうやってコントローラーにも書ける
スキーマはTypeを定義するだけで良さそう?
フロントエンドと併用するときだけ何かが必要なのかも
jsonファイルに型定義して、フロント側で型定義を再度しなくていい仕組みがあるか、作れるはず
GraphQL自体の型システムはここを見ればわかる
最初にQueryRootを定義する必要があって、それは普通QueryTypeになるっぽい?
そうではなくデータ取得の際の開始地点のようなオブジェクトかも
code: graphql
type Query {
User
}
この時のQuery
Query Mutation Subscriptionのことだと思われる = ルート型
code: ruby
class Schema < GraphQL::Schema
query QueryType
end
typeを定義して、スキーマに継承させる
アポロ
Use with Apollo Client
Apollo Client is a full featured, simple to use GraphQL client with convenient integrations for popular view layers. You don’t need to do anything special to connect Apollo Client to a graphql-ruby server.
接続の際に特別な設定は不要
実行
Schema.execute(query_string)
この場合は文字列が引数になる
見てみる
You can execute queries with your GraphQL::Schema and get a Ruby Hash as a result.
Rubyのハッシュが帰ってくる
Rails単体で使う時って、どんな感じなんだろう
ActiveRecordで取得した時よりも使い勝手は悪くなりそう、もちろん取得は色々楽になるのかもだけど
オプションがめっちゃある。GPT-4に解説してもらった
変数指定の実行
code: ruby
query_string = "
query getPost($postId: ID!) {
post(id: $postId) {
title
}
}"
variables = { "postId" => "1" }
MySchema.execute(query_string, variables: variables)
contextを使えばアプリケーション固有の様々な値を取れる
resolve functions
Schema#resolve_type hook
ID generation & fetching
current_userとかとれた
scoped context
子テーブルのオブジェクトにスコープを限ったcontextを渡すことができる。
そのポストの投稿者はログインユーザーと同じか?みたいな検証ができる。