graphql-batchでloadするデータにthenメソッドで処理を加える

こんにちは!kossyです!




さて、今回はgraphql-batchのthenメソッドを使って、loadしたobjectに処理を加える方法について、
ブログに残してみたいと思います。



環境

Ruby 2.6.3
Rails 6.0.3.4
graphql 1.11.6
graphql-batch 0.4.3



方法

post has_many comments という関連が組まれているとします。
この場合、 N + 1の発生を防ぐために、以下のようなタイプ定義を行うかと思います。

module Types
  class PostType < Types::BaseObject
    field :id, ID, null: true
    field :user_id, Integer, null: true
    field :title, String, null: true
    field :body, String, null: true
    field :status, Integer, null: true
    field :created_at, GraphQL::Types::ISO8601DateTime, null: true
    field :updated_at, GraphQL::Types::ISO8601DateTime, null: true
    field :comments, [Types::CommentType], null: true

    def comments
      Loaders::AssociationLoader.for(Post, :comments).load(object)
    end
  end
end

graphql-batchのforメソッドとloadメソッドを使って、オブジェクトのloadを行っています。

この時、thenメソッドを使うことで、後続の処理を加えることができます。

以下は、ActiveRecordのorderメソッドを使って、created_atで降順でsortしています。

    def comments
      Loaders::AssociationLoader.for(Post, :comments).load(object).then do |comments|
        comments.order(created_at: :desc)
      end
    end

f:id:kossy-web-engineer:20210214210343p:plain

添付画像はGraphQLのGUIクライアントであるAltairでcallした画像ですが、
created_atで降順でsortされていることがわかります。

また、thenメソッドはチェインして用いることができます。

    def likes
      Loaders::AssociationLoader.for(Post, :comments).load(object).then do |comments|
        Loaders::AssociationLoader.for(Comment, :likes).load(comments).then do |likes|
          likes.order(created_at: :desc)
        end  
      end
    end

上記のソースコードはcommentsについたいいねを降順で並び替えるような例になります。




勉強になりました。



大いに参考にさせていただいたサイト

この場を借りて御礼を申し上げます。