From 79a01358698ad3889b0c9a43cfb2f886fbae77e4 Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Wed, 23 Nov 2016 18:56:30 +0100 Subject: [PATCH] Cache accounts/:id/statuses and single statuses too --- app/controllers/api/v1/accounts_controller.rb | 22 ++++++++++++++++++- app/controllers/api/v1/statuses_controller.rb | 2 ++ 2 files changed, 23 insertions(+), 1 deletion(-) 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