From 1f2253545ba7a902212bace29f144a2246eeedab Mon Sep 17 00:00:00 2001
From: Paco Guzman <pacoguzmanp@gmail.com>
Date: Fri, 8 Jul 2016 18:42:47 +0200
Subject: [PATCH] Use cache for todos counter calling TodoService

---
 CHANGELOG                       |  1 +
 app/models/user.rb              |  4 ++--
 lib/api/todos.rb                |  2 +-
 spec/requests/api/todos_spec.rb | 12 ++++++++++++
 4 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/CHANGELOG b/CHANGELOG
index 6fe1720796dbf..c3b4c28dc8417 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -270,6 +270,7 @@ v 8.10.0
   - Fix new snippet style bug (elliotec)
   - Instrument Rinku usage
   - Be explicit to define merge request discussion variables
+  - Use cache for todos counter calling TodoService
   - Metrics for Rouge::Plugins::Redcarpet and Rouge::Formatters::HTMLGitlab
   - RailsCache metris now includes fetch_hit/fetch_miss and read_hit/read_miss info.
   - Allow [ci skip] to be in any case and allow [skip ci]. !4785 (simon_w)
diff --git a/app/models/user.rb b/app/models/user.rb
index 73368be7b1b17..87a2d999843d6 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -809,13 +809,13 @@ def update_cache_counts
 
   def todos_done_count(force: false)
     Rails.cache.fetch(['users', id, 'todos_done_count'], force: force) do
-      todos.done.count
+      TodosFinder.new(self, state: :done).execute.count
     end
   end
 
   def todos_pending_count(force: false)
     Rails.cache.fetch(['users', id, 'todos_pending_count'], force: force) do
-      todos.pending.count
+      TodosFinder.new(self, state: :pending).execute.count
     end
   end
 
diff --git a/lib/api/todos.rb b/lib/api/todos.rb
index 26c24c3baffcf..a90a667fafef1 100644
--- a/lib/api/todos.rb
+++ b/lib/api/todos.rb
@@ -73,7 +73,7 @@ def find_todos
       #
       delete do
         todos = find_todos
-        todos.each(&:done)
+        TodoService.new.mark_todos_as_done(todos, current_user)
 
         todos.length
       end
diff --git a/spec/requests/api/todos_spec.rb b/spec/requests/api/todos_spec.rb
index 3ccd0af652f7a..887a2ba5b8460 100644
--- a/spec/requests/api/todos_spec.rb
+++ b/spec/requests/api/todos_spec.rb
@@ -117,6 +117,12 @@
         expect(response.status).to eq(200)
         expect(pending_1.reload).to be_done
       end
+
+      it 'updates todos cache' do
+        expect_any_instance_of(User).to receive(:update_todos_count_cache).and_call_original
+
+        delete api("/todos/#{pending_1.id}", john_doe)
+      end
     end
   end
 
@@ -139,6 +145,12 @@
         expect(pending_2.reload).to be_done
         expect(pending_3.reload).to be_done
       end
+
+      it 'updates todos cache' do
+        expect_any_instance_of(User).to receive(:update_todos_count_cache).and_call_original
+
+        delete api("/todos", john_doe)
+      end
     end
   end
 
-- 
GitLab