0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

`graphql-ruby`で`Dataloader`を使う

Last updated at Posted at 2023-10-28

やる事

  1. graphql-rubyDataloaderを使用する宣言
  2. Dataloadermodelassociationsを事前読み込みする処理を実装
  3. 実装したDataloaderTypeクラスで仕様します

1. graphql-rubyDataloaderを使用する宣言

app_schema.rbdataloaderを有効化します。

app/graphql/app_schema.rb
class AppSchema < GraphQL::Schema
+  use GraphQL::Dataloader

  disable_introspection_entry_points unless Rails.env.development?
  
  query(QueryType)

  max_complexity 200
  max_depth 30
  default_page_size 50
  validate_max_errors 100
end

2. Dataloadermodelassociationsを事前読み込みする処理を実装

graphql-batchgemのリポジトリにActiveRecordPreloaderを扱うサンプルがあったので参考に以下のようにgraphql-rubyが提供しているdataloader機能で実装します

app/graphql/active_record_preloader.rb
# frozen_string_literal: true

class ActiveRecordPreloader < GraphQL::Dataloader::Source
  attr_reader :model, :association

  def initialize(model, association)
    @model = model
    @association = association
  end

  def fetch(records)
    validate!(records)
    ::ActiveRecord::Associations::Preloader.new(records:, associations: association).call
      records.map { |record| record.public_send(association) }
    end
  private

  def validate!(records)
    raise TypeError, "loader can't load association for #{model}" unless records.all? { |r| r.is_a?(model) }

    return if model.reflect_on_association(association)

    raise ArgumentError, "No association #{association} on #{model}"
  end
end

3. 実装したDataloaderTypeクラスで仕様します

以下のように、dataloader.withメソッドの引数に

  • 作成したActiveRecordPreloader
  • ActiveRecordmodel
  • modelに紐づくpreloadしたいassociation

を指定します

app/graphql/user_type.rb
class UserType < Types::BaseObject
  field :email, String, null: false
  field :user_post, UserPostType, null: false

  def profile
    dataloader.with(ActiveRecordPreloader, ::User, :user_post).load(object)
  end
end

参考

環境

  • ruby 3.2.2
  • rails 7.0.8
  • graphql 2.1.0
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?