Skip to content

Commit

Permalink
Merge pull request #2650 from pulibrary/issue_2637_homepage_cache
Browse files Browse the repository at this point in the history
Caches the Solr data for the home page
  • Loading branch information
hackartisan authored Aug 12, 2021
2 parents db13d87 + 19cef20 commit 4de4004
Show file tree
Hide file tree
Showing 3 changed files with 631 additions and 1 deletion.
46 changes: 45 additions & 1 deletion app/controllers/catalog_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -670,8 +670,52 @@ def render_search_results_as_json
end

def index
super
if home_page?
render_empty_search
else
super
end
rescue ActionController::BadRequest
render file: Rails.public_path.join('x400.html'), layout: true, status: :bad_request
end

private

def render_empty_search
# This code is a copy of Blacklight::Catalog.index() method but adapted to use
# a cached version of the data rather than requesting the data from Solr.
# See https://github.com/projectblacklight/blacklight/blob/v7.0.1/app/controllers/concerns/blacklight/catalog.rb#L25-L41
@response = empty_solr_response
@document_list = @response.documents
respond_to do |format|
format.html { store_preferred_view }
format.rss { render layout: false }
format.atom { render layout: false }
format.json do
@presenter = Blacklight::JsonPresenter.new(@response, blacklight_config)
end
additional_response_formats(format)
document_export_formats(format)
end
end

def home_page?
# When only the "controller" and "action" keys are in the request (i.e. no query or facets)
# we consider it the home page.
params.keys.count == 2
end

def empty_solr_response
raw_response = JSON.parse(empty_raw_response)
Blacklight::Solr::Response.new(raw_response, raw_response["responseHeader"]["params"], blacklight_config: @blacklight_config)
end

def empty_raw_response
Rails.cache.fetch("home_page_empty_raw_response", expires_in: 3.hours) do
Rails.logger.info "Cached home page results"
# We cannot cache the Blacklight::Solr::Response as-is so we convert it to JSON first
(response, _deprecated_document_list) = search_service.search_results
response.to_json
end
end
end
20 changes: 20 additions & 0 deletions spec/controllers/catalog_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,24 @@
expect(assigns(:hathi_url)).to be_nil
end
end

describe 'home page' do
let(:solr_empty_query) { File.open(fixture_path + '/solr_empty_query.json').read }

before do
allow(Rails.cache).to receive(:fetch).and_return solr_empty_query
end

it 'uses the cache for an empty search' do
get :index, params: {}
expect(response.status).to eq 200
expect(Rails.cache).to have_received(:fetch)
end

it 'does not use the cache for a search with arguments' do
get :index, params: { q: "coffee" }
expect(response.status).to eq 200
expect(Rails.cache).not_to have_received(:fetch)
end
end
end
Loading

0 comments on commit 4de4004

Please sign in to comment.