about summary refs log tree commit diff
diff options
context:
space:
mode:
authorEugen Rochko <eugen@zeonfederated.com>2016-11-23 18:56:30 +0100
committerEugen Rochko <eugen@zeonfederated.com>2016-11-23 19:00:43 +0100
commit79a01358698ad3889b0c9a43cfb2f886fbae77e4 (patch)
treeb687636c1179a0c831acbbe10d8342a8c8f2e6b4
parent2112a81e869fe342d7351b1fb1951df754a5d255 (diff)
Cache accounts/:id/statuses and single statuses too
-rw-r--r--app/controllers/api/v1/accounts_controller.rb22
-rw-r--r--app/controllers/api/v1/statuses_controller.rb2
2 files changed, 23 insertions, 1 deletions
diff --git a/app/controllers/api/v1/accounts_controller.rb b/app/controllers/api/v1/accounts_controller.rb
index 97d626af2..4ae900583 100644
--- a/app/controllers/api/v1/accounts_controller.rb
+++ b/app/controllers/api/v1/accounts_controller.rb
@@ -57,7 +57,8 @@ class Api::V1::AccountsController < ApiController
   end
 
   def statuses
-    @statuses = @account.statuses.with_includes.paginate_by_max_id(DEFAULT_STATUSES_LIMIT, params[:max_id], params[:since_id]).to_a
+    @statuses = @account.statuses.paginate_by_max_id(DEFAULT_STATUSES_LIMIT, params[:max_id], params[:since_id]).to_a
+    @statuses = cache(@statuses)
 
     set_maps(@statuses)
     set_counters_maps(@statuses)
@@ -120,4 +121,23 @@ class Api::V1::AccountsController < ApiController
     @followed_by = Account.followed_by_map([@account.id], current_user.account_id)
     @blocking    = Account.blocking_map([@account.id], current_user.account_id)
   end
+
+  def cache(raw)
+    uncached_ids           = []
+    cached_keys_with_value = Rails.cache.read_multi(*raw.map(&:cache_key))
+
+    raw.each do |status|
+      uncached_ids << status.id unless cached_keys_with_value.key?(status.cache_key)
+    end
+
+    unless uncached_ids.empty?
+      uncached = Status.where(id: uncached_ids).with_includes.map { |s| [s.id, s] }.to_h
+
+      uncached.values.each do |status|
+        Rails.cache.write(status.cache_key, status)
+      end
+    end
+
+    raw.map { |status| cached_keys_with_value[status.cache_key] || uncached[status.id] }
+  end
 end
diff --git a/app/controllers/api/v1/statuses_controller.rb b/app/controllers/api/v1/statuses_controller.rb
index 2e0399301..a693ce00d 100644
--- a/app/controllers/api/v1/statuses_controller.rb
+++ b/app/controllers/api/v1/statuses_controller.rb
@@ -9,6 +9,8 @@ class Api::V1::StatusesController < ApiController
   respond_to :json
 
   def show
+    cached  = Rails.cache.read(@status.cache_key)
+    @status = cached unless cached.nil?
   end
 
   def context