class Excon::HyperMedia::Middlewares::HypertextCachePattern

HypertextCachePattern

This middleware handles hcp-enabled requests.

@see: tools.ietf.org/html/draft-kelly-json-hal-06#section-8.3

Attributes

datum[R]

Public Instance Methods

request_call(datum) click to toggle source
Calls superclass method
# File lib/excon/hypermedia/middlewares/hypertext_cache_pattern.rb, line 15
def request_call(datum)
  @datum = datum

  if stubs.any?
    # We've created new stubs.  The request should be marked as `mocked`
    # to make sure the stubbed response is returned.
    datum[:mock] = true

    # The requested resource might not be part of the embedded resources
    # so we allow external requests.
    # datum[:allow_unstubbed_requests] = true

    # Make sure Excon's `Mock` middleware runs after this middleware, as
    # it might have already triggered in the middleware chain.
    orig_stack = @stack
    @stack = Excon::Middleware::Mock.new(orig_stack)
  end

  super
rescue StandardError => e
  raise unless e.class == Excon::Errors::StubNotFound

  # If a request was made to a non-stubbed resource, don't use the Mock
  # middleware, but simply send the request to the server.
  @stack = orig_stack
  super
end
response_call(datum) click to toggle source
Calls superclass method
# File lib/excon/hypermedia/middlewares/hypertext_cache_pattern.rb, line 43
def response_call(datum)
  @datum = datum

  # After the response is returned, remove any request-specific stubs
  # from Excon, so they can't be accidentally re-used anymore.
  embedded.each { |r| (match = matcher(r)) && Excon.unstub(match) }

  super
end

Private Instance Methods

embedded() click to toggle source
# File lib/excon/hypermedia/middlewares/hypertext_cache_pattern.rb, line 78
def embedded
  datum[:embedded].to_h.values.flatten
end
matcher(resource) click to toggle source
# File lib/excon/hypermedia/middlewares/hypertext_cache_pattern.rb, line 59
def matcher(resource)
  return unless (uri = ::Addressable::URI.parse(resource.dig('_links', 'self', 'href')))

  {
    scheme: uri.scheme,
    host:   uri.host,
    path:   uri.path,
    query:  uri.query
  }
end
response(resource) click to toggle source
# File lib/excon/hypermedia/middlewares/hypertext_cache_pattern.rb, line 70
def response(resource)
  {
    body:      resource.to_json,
    hcp:       true,
    headers:   { 'Content-Type' => 'application/hal+json', 'X-HCP' => 'true' }
  }
end
stubs() click to toggle source
# File lib/excon/hypermedia/middlewares/hypertext_cache_pattern.rb, line 55
def stubs
  embedded.each { |r| (match = matcher(r)) && Excon.stub(match, response(r)) }.compact
end