From eca9fd4e0cdec7ed0fda73951e743c691cca74e1 Mon Sep 17 00:00:00 2001 From: Gregor Billing Date: Sun, 5 Nov 2023 10:04:20 +0100 Subject: [PATCH] Switch API search to RO replica only during actual search (#8490) --- .../app/controllers/api/v0/api_controller.rb | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/WcaOnRails/app/controllers/api/v0/api_controller.rb b/WcaOnRails/app/controllers/api/v0/api_controller.rb index 2b4c34b042..8f60b19927 100644 --- a/WcaOnRails/app/controllers/api/v0/api_controller.rb +++ b/WcaOnRails/app/controllers/api/v0/api_controller.rb @@ -90,19 +90,23 @@ def help end def search(*models) - ActiveRecord::Base.connected_to(role: :read_replica) do - query = params[:q]&.slice(0...SearchResultsController::SEARCH_QUERY_LIMIT) - unless query - render status: :bad_request, json: { error: "No query specified" } - return - end - concise_results_date = ComputeAuxiliaryData.end_date || Date.current - cache_key = ["search", *models, concise_results_date.iso8601, query] - result = Rails.cache.fetch(cache_key) do + query = params[:q]&.slice(0...SearchResultsController::SEARCH_QUERY_LIMIT) + + unless query + render status: :bad_request, json: { error: "No query specified" } + return + end + + concise_results_date = ComputeAuxiliaryData.end_date || Date.current + cache_key = ["search", *models, concise_results_date.iso8601, query] + + result = Rails.cache.fetch(cache_key) do + ActiveRecord::Base.connected_to(role: :read_replica) do models.flat_map { |model| model.search(query, params: params).limit(DEFAULT_API_RESULT_LIMIT) } end - render status: :ok, json: { result: result } end + + render status: :ok, json: { result: result } end def posts_search