Class: GraphQL::Cache::Marshal

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/cache/marshal.rb

Overview

Used to marshal cache fetches into either writes or reads

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Marshal

Initialize a new instance of GraphQL::Cache::Marshal



23
24
25
# File 'lib/graphql/cache/marshal.rb', line 23

def initialize(key)
  self.key = key.to_s
end

Instance Attribute Details

#keyString

The cache key to marshal around

Returns:

  • (String)

    The cache key



12
13
14
# File 'lib/graphql/cache/marshal.rb', line 12

def key
  @key
end

Class Method Details

.[](key) ⇒ GraphQL::Cache::Marshal

Initializer helper to allow syntax like Marshal[key].read(config, &block)



18
19
20
# File 'lib/graphql/cache/marshal.rb', line 18

def self.[](key)
  new(key)
end

Instance Method Details

#read(config, force: false, &block) ⇒ Object

Read a value from cache if it exists and re-hydrate it or execute the block and write it's result to cache

Parameters:

  • config (Hash)

    The object passed to cache: on the field definition

Returns:

  • (Object)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/graphql/cache/marshal.rb', line 32

def read(config, force: false, &block)
  # write new data from resolver if forced
  return write(config, &block) if force

  cached = cache.read(key)

  if cached.nil?
    logger.debug "Cache miss: (#{key})"
    write config, &block
  else
    logger.debug "Cache hit: (#{key})"
    cached
  end
end

#write(config) ⇒ Object

Executes the resolution block and writes the result to cache

Parameters:

  • config (Hash)

    The middleware resolution config hash

See Also:

  • Deconstruct#perform


51
52
53
54
55
56
57
# File 'lib/graphql/cache/marshal.rb', line 51

def write(config)
  resolved = yield
  document = Deconstructor[resolved].perform

  cache.write(key, document, expires_in: expiry(config))
  resolved
end