Class: TocDoc::Middleware::Cache

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/toc_doc/http/middleware/cache.rb

Overview

Faraday middleware that caches successful GET responses.

Cache hits bypass all downstream middleware (retry, rate-limiting, JSON parsing, and the HTTP adapter). The cached body is the already-parsed object returned by the JSON middleware on the original miss.

Only GET requests with 200 responses are cached. All other verbs and non-200 responses flow through normally.

The cache key is built from the full URL with query parameters sorted for determinism.

Stack position (outermost first): RaiseError > Cache > Logging > Retry > RateLimiter > JSON > Adapter

Examples:

store = TocDoc::Cache::MemoryStore.new
builder.use TocDoc::Middleware::Cache, store: store, ttl: 300

Instance Method Summary collapse

Constructor Details

#initialize(app, store:, ttl: 300) ⇒ Cache

Returns a new instance of Cache.

Parameters:

  • app (#call)

    the next middleware in the stack

  • store (#read, #write)

    a cache store (MemoryStore or AS-compatible)

  • ttl (Numeric) (defaults to: 300)

    TTL in seconds for cached responses (default: 300)



30
31
32
33
34
# File 'lib/toc_doc/http/middleware/cache.rb', line 30

def initialize(app, store:, ttl: 300)
  super(app)
  @store = store
  @ttl   = ttl
end

Instance Method Details

#call(env) ⇒ Faraday::Response

Serves from cache on hit; fetches and caches on miss.

Parameters:

  • env (Faraday::Env)

    the request environment

Returns:

  • (Faraday::Response)


40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/toc_doc/http/middleware/cache.rb', line 40

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

  cache_key = build_key(env)
  cached = @store.read(cache_key)
  return cached_response(env, cached) if cached

  @app.call(env).on_complete do |response_env|
    next unless response_env.status == 200

    @store.write(cache_key, response_env.body, expires_in: @ttl)
  end
end