Skip to content

Commit a9a5fc1

Browse files
committed
Added support of unchanged requests
Added middleware for correct support status 304 in responses It gives huge speed boost, if you have to request same resources offten
1 parent 0ca03e2 commit a9a5fc1

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

lib/her/middleware.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
require "her/middleware/first_level_parse_json"
33
require "her/middleware/second_level_parse_json"
44
require "her/middleware/accept_json"
5+
require "her/middleware/cache_unmodified"
56

67
module Her
78
module Middleware
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Easy way to begin support 304 status, so on ther side if data was not changed
2+
# You will load it from local cache. Of course, other side must support
3+
# Of course, other side must support 304 status also.
4+
# Here is Rails controller example with this support:
5+
#
6+
# class Post < ApplicationController
7+
# before_action :check_changes
8+
#
9+
# private
10+
#
11+
# def check_changes
12+
# return unless request.headers['HTTP_IF_MODIFIED_SINCE']
13+
# return if request.headers['HTTP_IF_MODIFIED_SINCE'].to_datetime > resource.updated_at
14+
# render body: nil, status: 304
15+
# end
16+
# end
17+
class Her::Middleware::CacheUnmodified < Faraday::Middleware
18+
SAVE_METHODS = [:get, :head].freeze
19+
CACHE_KEY_TTL = 1.week.freeze
20+
21+
attr_reader :cache, :cache_key_prefix
22+
attr_accessor :url
23+
def initialize(app, cache: Rails.cache, cache_key_prefix: nil)
24+
@app = app
25+
@cache = cache
26+
@cache_key_prefix = cache_key_prefix
27+
end
28+
29+
def call(env)
30+
return @app.call(env) unless SAVE_METHODS.include?(env[:method])
31+
self.url = env.url.to_s
32+
env[:request_headers]["If-Modified-Since"] ||= cached_time if cached_time
33+
34+
@app.call(env).on_complete do
35+
if env[:status] == 304
36+
if cached_body
37+
env[:body] = cached_body
38+
# with out this hack Her crushes
39+
env[:status] = 200
40+
end
41+
elsif env[:status] == 200
42+
cache.write cache_key_body, env[:body], expires_in: CACHE_KEY_TTL
43+
cache.write cache_key_time, Time.zone.now.httpdate, expires_in: CACHE_KEY_TTL
44+
end
45+
end
46+
end
47+
48+
private
49+
50+
def cache_key_time
51+
@cache_key_time ||= [@cache_key_prefix, "time", url].compact.join("/")
52+
end
53+
54+
def cache_key_body
55+
@cache_key_body ||= [@cache_key_prefix, "body", url].compact.join("/")
56+
end
57+
58+
def cached_time
59+
@cached_time ||= cache.read(cache_key_time)
60+
end
61+
62+
def cached_body
63+
@cached_body ||= cache.read(cache_key_body)
64+
end
65+
end

0 commit comments

Comments
 (0)