class GraphQL::Cache::Deconstructor

GraphQL objects can't be serialized to cache so we have to maintain an abstraction between the raw cache value and the GraphQL expected object. This class exposes methods for deconstructing an object to be stored in cache

Attributes

method[RW]

A flag indicating the type of object construction to use when building a new GraphQL object. Can be one of 'array', 'collectionproxy', 'relation'. These values have been chosen because it is easy to use the class names of the possible object types for this purpose.

@return [String] 'array' or 'collectionproxy' or 'relation'

raw[RW]

The raw value to perform actions on. Could be a raw cached value, or a raw GraphQL Field.

@return [Object]

Public Class Methods

[](raw) click to toggle source

Initializer helper that generates a valid `method` string based on `raw.class.name`.

@return [Object] A newly initialized GraphQL::Cache::Deconstructor instance

# File lib/graphql/cache/deconstructor.rb, line 28
def self.[](raw)
  build_method = namify(raw.class.name)
  new(raw, build_method)
end
namify(str) click to toggle source

Ruby-only means of “demodularizing” a string

# File lib/graphql/cache/deconstructor.rb, line 34
def self.namify(str)
  str.split('::').last.downcase
end
new(raw, method) click to toggle source
# File lib/graphql/cache/deconstructor.rb, line 38
def initialize(raw, method)
  self.raw    = raw
  self.method = method
end

Public Instance Methods

deconstruct_array(raw) click to toggle source

@private

# File lib/graphql/cache/deconstructor.rb, line 57
def deconstruct_array(raw)
  return [] if raw.empty?

  if raw.first.class.ancestors.include? GraphQL::Schema::Object
    raw.map(&:object)
  else
    raw
  end
end
deconstruct_object(raw) click to toggle source

@private

# File lib/graphql/cache/deconstructor.rb, line 68
def deconstruct_object(raw)
  if raw.respond_to?(:object)
    raw.object
  else
    raw
  end
end
perform() click to toggle source

Deconstructs a GraphQL field into a cachable value

@return [Object] A value suitable for writing to cache

# File lib/graphql/cache/deconstructor.rb, line 46
def perform
  if %(array collectionproxy).include? method
    deconstruct_array(raw)
  elsif raw.class.ancestors.include? GraphQL::Relay::BaseConnection
    raw.nodes
  else
    deconstruct_object(raw)
  end
end