Skip to content

Commit

Permalink
also cache nil (doc not found) to avoid multiple requests
Browse files Browse the repository at this point in the history
  • Loading branch information
langalex committed Apr 5, 2024
1 parent 0a321cc commit a93100e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 18 deletions.
4 changes: 2 additions & 2 deletions lib/couch_potato/database.rb
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def load_document(id)

cached = cache && cache[id]
if cache
if cached
if cache.key?(id)
ActiveSupport::Notifications.instrument('couch_potato.load.cached', id: id, doc: cached) do
cached
end
Expand Down Expand Up @@ -178,7 +178,7 @@ def load_documents(ids)
if cache
uncached_ids.each do |id|
doc = uncached_docs_by_id[id]
cache[id] = doc if doc
cache[id] = doc
end
end
ids.filter_map { |id| (cached_docs_by_id[id]) || uncached_docs_by_id[id] }
Expand Down
36 changes: 20 additions & 16 deletions spec/unit/caching_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@
db.load '1'
end

it 'caches nil' do
allow(couchrest_db).to receive(:get).with('1').and_return(nil)

db.load '1'
db.load '1'

expect(couchrest_db).to have_received(:get).with('1').exactly(1).times
end

it 'gets an object from the cache the 2nd time via #load!' do
expect(couchrest_db).to receive(:get).with('1').exactly(1).times

Expand Down Expand Up @@ -92,6 +101,17 @@
expect(couchrest_db).to have_received(:bulk_load).with(['2']).exactly(1).times
end

it 'caches nil' do
allow(couchrest_db).to receive(:bulk_load).with(['1']).and_return('rows' => [{'doc' => nil}])
allow(couchrest_db).to receive(:bulk_load).with(['2']).and_return('rows' => [{'doc' => doc2}])


db.load_document(['1'])
db.load_document(['1', '2'])

expect(couchrest_db).to have_received(:bulk_load).with(['1']).exactly(1).times
end

it 'instruments the load call' do
allow(couchrest_db).to receive(:bulk_load).with(['1'])
.and_return('rows' => [{'doc' => doc1}])
Expand Down Expand Up @@ -137,22 +157,6 @@

expect(result).to eql([doc1, doc2])
end

it 'does not cache documents that do not respond to id' do
doc1 = {
'id' => '1',
}
doc2 = {
'id' => '2',
}
allow(couchrest_db).to receive(:bulk_load).with(['1', '2'])
.and_return('rows' => [{'doc' => doc1}, {'doc' => doc2}])

db.load_document(['1', '2'])
db.load_document(['1', '2'])

expect(couchrest_db).to have_received(:bulk_load).with(['1', '2']).exactly(2).times
end
end

context 'when switching the database' do
Expand Down

0 comments on commit a93100e

Please sign in to comment.