Class: TocDoc::Middleware::Cache
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- TocDoc::Middleware::Cache
- 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
Instance Method Summary collapse
-
#call(env) ⇒ Faraday::Response
Serves from cache on hit; fetches and caches on miss.
-
#initialize(app, store:, ttl: 300) ⇒ Cache
constructor
A new instance of Cache.
Constructor Details
#initialize(app, store:, ttl: 300) ⇒ Cache
Returns a new instance of Cache.
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.
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 |