Class: GraphQL::Sources::RailsCache

Inherits:
Dataloader::Source
  • Object
show all
Defined in:
lib/graphql/sources/rails_cache.rb

Overview

A class for loading with Rails.cache.

class UserType < GraphQL::Schema::Object
  field :location, String, null: false

  def location
    dataloader
      .with(GraphQL::Sources::RailsCache)
      .load(key: "geocode:#{object.latest_ip}", fallback: -> { Geocode.for(object.latest_ip) })
  end
end

Instance Method Summary collapse

Instance Method Details

#fetch(operations) ⇒ Object

Parameters:

  • operations (Array<Hash>)

    an array of key and fallback hashes



18
19
20
21
22
23
# File 'lib/graphql/sources/rails_cache.rb', line 18

def fetch(operations)
  keys = operations.pluck(:key)
  fallbacks = operations.to_h { |operation| [operation[:key], operation[:fallback]] }
  results = Rails.cache.fetch_multi(*keys) { |key| fallbacks[key].call }
  keys.map { |key| results[key] }
end