From cf912e01fd74e7320eb4027c35f7744a36d2f2b8 Mon Sep 17 00:00:00 2001 From: Eugen Rochko Date: Wed, 23 Nov 2016 08:34:35 +0100 Subject: Implement includes caching for timelines APIs --- app/controllers/api/v1/timelines_controller.rb | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'app/controllers/api') diff --git a/app/controllers/api/v1/timelines_controller.rb b/app/controllers/api/v1/timelines_controller.rb index c5ed315d9..b1d7c3052 100644 --- a/app/controllers/api/v1/timelines_controller.rb +++ b/app/controllers/api/v1/timelines_controller.rb @@ -38,6 +38,7 @@ class Api::V1::TimelinesController < ApiController def public @statuses = Status.as_public_timeline(current_account).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) @@ -54,6 +55,7 @@ class Api::V1::TimelinesController < ApiController def tag @tag = Tag.find_by(name: params[:id].downcase) @statuses = @tag.nil? ? [] : Status.as_tag_timeline(@tag, current_account).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) @@ -66,4 +68,25 @@ class Api::V1::TimelinesController < ApiController render action: :index end + + private + + 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 -- cgit