Class: Fme::Api::FaradayCacheServiceDown

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/fme/api/faraday_cache_service_down.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, cache = nil, cache_identifier = 'empty') ⇒ FaradayCacheServiceDown

Returns a new instance of FaradayCacheServiceDown.



9
10
11
12
13
# File 'lib/fme/api/faraday_cache_service_down.rb', line 9

def initialize(app, cache = nil, cache_identifier = 'empty')
  super(app)
  @cache = cache
  @cache_identifier = cache_identifier
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



6
7
8
# File 'lib/fme/api/faraday_cache_service_down.rb', line 6

def cache
  @cache
end

#cache_identifierObject (readonly)

Returns the value of attribute cache_identifier.



7
8
9
# File 'lib/fme/api/faraday_cache_service_down.rb', line 7

def cache_identifier
  @cache_identifier
end

Instance Method Details

#cache_key(env) ⇒ Object



43
44
45
46
47
# File 'lib/fme/api/faraday_cache_service_down.rb', line 43

def cache_key(env)
  url = env[:url].dup
  url.normalize!
  "service_down:#{url.request_uri}:#{cache_identifier}"
end

#call(env) ⇒ Object



15
16
17
18
# File 'lib/fme/api/faraday_cache_service_down.rb', line 15

def call(env)
  @app.call(env) && return unless :get == env[:method]
  make_get_request(env)
end

#create_response(env) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/fme/api/faraday_cache_service_down.rb', line 20

def create_response(env)
  hash = env.to_hash

  {
    status: hash[:status],
    body: hash[:body],
    response_headers: hash[:response_headers]
  }
end

#make_get_request(env) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/fme/api/faraday_cache_service_down.rb', line 30

def make_get_request(env)
  @app.call(env).on_complete do |response_env|
    cache.write(cache_key(env), create_response(response_env))
    response_env
  end
rescue Faraday::TimeoutError
  cached_response = cache.read(cache_key(env))
  raise unless cached_response.present?
  Rails.logger.warn "responding to #{cache_key(env)} request from cache"
  env.update(cached_response)
  Faraday::Response.new(env)
end