Skip to content

Commit

Permalink
Added support of unchanged requests
Browse files Browse the repository at this point in the history
Added middleware for correct support status 304 in responses

It gives huge speed boost, if you have to

request same resources offten
  • Loading branch information
kvokka committed Feb 1, 2017
1 parent 0ca03e2 commit a9a5fc1
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/her/middleware.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
require "her/middleware/first_level_parse_json"
require "her/middleware/second_level_parse_json"
require "her/middleware/accept_json"
require "her/middleware/cache_unmodified"

module Her
module Middleware
Expand Down
65 changes: 65 additions & 0 deletions lib/her/middleware/cache_unmodified.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Easy way to begin support 304 status, so on ther side if data was not changed
# You will load it from local cache. Of course, other side must support
# Of course, other side must support 304 status also.
# Here is Rails controller example with this support:
#
# class Post < ApplicationController
# before_action :check_changes
#
# private
#
# def check_changes
# return unless request.headers['HTTP_IF_MODIFIED_SINCE']
# return if request.headers['HTTP_IF_MODIFIED_SINCE'].to_datetime > resource.updated_at
# render body: nil, status: 304
# end
# end
class Her::Middleware::CacheUnmodified < Faraday::Middleware
SAVE_METHODS = [:get, :head].freeze
CACHE_KEY_TTL = 1.week.freeze

attr_reader :cache, :cache_key_prefix
attr_accessor :url
def initialize(app, cache: Rails.cache, cache_key_prefix: nil)
@app = app
@cache = cache
@cache_key_prefix = cache_key_prefix
end

def call(env)
return @app.call(env) unless SAVE_METHODS.include?(env[:method])
self.url = env.url.to_s
env[:request_headers]["If-Modified-Since"] ||= cached_time if cached_time

@app.call(env).on_complete do
if env[:status] == 304
if cached_body
env[:body] = cached_body
# with out this hack Her crushes
env[:status] = 200
end
elsif env[:status] == 200
cache.write cache_key_body, env[:body], expires_in: CACHE_KEY_TTL
cache.write cache_key_time, Time.zone.now.httpdate, expires_in: CACHE_KEY_TTL
end
end
end

private

def cache_key_time
@cache_key_time ||= [@cache_key_prefix, "time", url].compact.join("/")
end

def cache_key_body
@cache_key_body ||= [@cache_key_prefix, "body", url].compact.join("/")
end

def cached_time
@cached_time ||= cache.read(cache_key_time)
end

def cached_body
@cached_body ||= cache.read(cache_key_body)
end
end

0 comments on commit a9a5fc1

Please sign in to comment.