Class: GraphQL::Doctor::Cache

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

Constant Summary collapse

FORMAT_VERSION =
3

Instance Method Summary collapse

Constructor Details

#initialize(directory: ".graphql-doctor/cache") ⇒ Cache

Returns a new instance of Cache.



13
14
15
# File 'lib/graphql/doctor/cache.rb', line 13

def initialize(directory: ".graphql-doctor/cache")
  @directory = directory
end

Instance Method Details

#fetch(path, config_digest: "") ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/graphql/doctor/cache.rb', line 17

def fetch(path, config_digest: "")
  begin
    source = File.binread(path)
  rescue SystemCallError
    return yield
  end

  key = Digest::SHA256.hexdigest(
    [File.expand_path(path), source, VERSION, FORMAT_VERSION, config_digest].join("\0")
  )
  cache_path = File.join(@directory, "#{key}.json")
  if File.file?(cache_path)
    begin
      return Source::Index.from_h(JSON.parse(File.read(cache_path)))
    rescue StandardError
      nil
    end
  end

  value = yield(source)
  begin
    FileUtils.mkdir_p(@directory)
    File.write(cache_path, JSON.generate(value.to_h))
  rescue SystemCallError
    nil
  end
  value
end