Sha256: 665a60016cb5332bf16a6fbbaea6869173c6222ec31d3b20dbe37fbe973bfdd5

Contents?: true

Size: 1.16 KB

Versions: 13

Compression:

Stored size: 1.16 KB

Contents

# frozen_string_literal: true

require "n1_loader/ar_lazy_preload"
require 'graphql'

require_relative 'context/setup_database'
require_relative 'context/setup_ar_lazy'

class User < ActiveRecord::Base
  has_many :payments

  n1_optimized :payments_total do |users|
    total_per_user = Payment.group(:user_id).where(user: users).sum(:amount).tap { |h| h.default = 0 }

    users.each do |user|
      total = total_per_user[user.id]
      fulfill(user, total)
    end
  end
end

class Payment < ActiveRecord::Base
  belongs_to :user

  validates :amount, presence: true
end

10.times do
  user = User.create!
  10.times do
    Payment.create!(user: user, amount: rand(1000))
  end
end

ArLazyPreload.config.auto_preload = true
# Or use +preload_associations_lazily+ when loading objects from database

class UserType < GraphQL::Schema::Object
  field :payments_total, Integer
end

class QueryType < GraphQL::Schema::Object
  field  :users, [UserType]

  def users
    User.all
  end
end

class Schema < GraphQL::Schema
  query QueryType
end

query_string = <<~GQL
  {
    users {
      paymentsTotal
    }
  }
GQL

# No N+1. And never will be!
p Schema.execute(query_string)['data']

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
n1_loader-1.7.2 examples/graphql.rb
n1_loader-1.7.1 examples/graphql.rb
n1_loader-1.7.0 examples/graphql.rb
n1_loader-1.6.6 examples/graphql.rb
n1_loader-1.6.5 examples/graphql.rb
n1_loader-1.6.4 examples/graphql.rb
n1_loader-1.6.3 examples/graphql.rb
n1_loader-1.6.2 examples/graphql.rb
n1_loader-1.6.1 examples/graphql.rb
n1_loader-1.6.0 examples/graphql.rb
n1_loader-1.5.1 examples/graphql.rb
n1_loader-1.5.0 examples/graphql.rb
n1_loader-1.4.4 examples/graphql.rb