about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--app/services/search_service.rb21
1 files changed, 21 insertions, 0 deletions
diff --git a/app/services/search_service.rb b/app/services/search_service.rb
index 73ff785c9..0ef3f4a00 100644
--- a/app/services/search_service.rb
+++ b/app/services/search_service.rb
@@ -24,6 +24,7 @@ class SearchService < BaseService
 
   def search_for
     results = Status.search_for(@query.gsub(/\A#/, ''), @account, @limit, @offset)
+    cache_collection results, Status
   end
 
   def perform_accounts_search!
@@ -97,4 +98,24 @@ class SearchService < BaseService
       domain_blocking_by_domain: Account.domain_blocking_map_by_domain(domains, account.id),
     }
   end
+
+	def cache_collection(raw, klass)
+    return raw unless klass.respond_to?(:with_includes)
+
+    raw                    = raw.cache_ids.to_a if raw.is_a?(ActiveRecord::Relation)
+    cached_keys_with_value = Rails.cache.read_multi(*raw).transform_keys(&:id)
+    uncached_ids           = raw.map(&:id) - cached_keys_with_value.keys
+
+    klass.reload_stale_associations!(cached_keys_with_value.values) if klass.respond_to?(:reload_stale_associations!)
+
+    unless uncached_ids.empty?
+      uncached = klass.where(id: uncached_ids).with_includes.each_with_object({}) { |item, h| h[item.id] = item }
+
+      uncached.each_value do |item|
+        Rails.cache.write(item, item)
+      end
+    end
+
+    raw.map { |item| cached_keys_with_value[item.id] || uncached[item.id] }.compact
+  end
 end