diff options
author | Eugen Rochko <eugen@zeonfederated.com> | 2016-11-23 08:34:35 +0100 |
---|---|---|
committer | Eugen Rochko <eugen@zeonfederated.com> | 2016-11-23 08:34:35 +0100 |
commit | cf912e01fd74e7320eb4027c35f7744a36d2f2b8 (patch) | |
tree | 53ae364786c70f0aff47e3ea6086c0ac821f4269 /app/controllers/api/v1 | |
parent | 5c78547198de20e7f367adb142acc82cd80b4899 (diff) |
Implement includes caching for timelines APIs
Diffstat (limited to 'app/controllers/api/v1')
-rw-r--r-- | app/controllers/api/v1/timelines_controller.rb | 23 |
1 files changed, 23 insertions, 0 deletions
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 |