From 78ebdf88e9651113e98e11536c140fb9d4b1bbe4 Mon Sep 17 00:00:00 2001 From: Victor Baranov Date: Fri, 20 Sep 2024 12:05:07 +0300 Subject: [PATCH] fix: Set min query length in the search API endpoints (#10698) --- .../controllers/api/v2/search_controller.ex | 22 +++++++++++++++++++ .../controllers/search_controller.ex | 12 ++++++++++ 2 files changed, 34 insertions(+) diff --git a/apps/block_scout_web/lib/block_scout_web/controllers/api/v2/search_controller.ex b/apps/block_scout_web/lib/block_scout_web/controllers/api/v2/search_controller.ex index 0a3c0f17ae..af3324ad10 100644 --- a/apps/block_scout_web/lib/block_scout_web/controllers/api/v2/search_controller.ex +++ b/apps/block_scout_web/lib/block_scout_web/controllers/api/v2/search_controller.ex @@ -8,6 +8,16 @@ defmodule BlockScoutWeb.API.V2.SearchController do alias Explorer.PagingOptions @api_true [api?: true] + @min_query_length 3 + + def search(conn, %{"q" => query}) when byte_size(query) < @min_query_length do + conn + |> put_status(200) + |> render(:search_results, %{ + search_results: [], + next_page_params: nil + }) + end def search(conn, %{"q" => query} = params) do [paging_options: paging_options] = paging_options(params) @@ -29,6 +39,12 @@ defmodule BlockScoutWeb.API.V2.SearchController do }) end + def check_redirect(conn, %{"q" => query}) when byte_size(query) < @min_query_length do + conn + |> put_status(200) + |> render(:search_results, %{result: {:error, :not_found}}) + end + def check_redirect(conn, %{"q" => query}) do result = query @@ -40,6 +56,12 @@ defmodule BlockScoutWeb.API.V2.SearchController do |> render(:search_results, %{result: result}) end + def quick_search(conn, %{"q" => query}) when byte_size(query) < @min_query_length do + conn + |> put_status(200) + |> render(:search_results, %{search_results: []}) + end + def quick_search(conn, %{"q" => query}) do search_results = Search.balanced_unpaginated_search(%PagingOptions{page_size: 50}, query, @api_true) diff --git a/apps/block_scout_web/lib/block_scout_web/controllers/search_controller.ex b/apps/block_scout_web/lib/block_scout_web/controllers/search_controller.ex index 937c4b2603..a797076826 100644 --- a/apps/block_scout_web/lib/block_scout_web/controllers/search_controller.ex +++ b/apps/block_scout_web/lib/block_scout_web/controllers/search_controller.ex @@ -7,6 +7,18 @@ defmodule BlockScoutWeb.SearchController do alias Explorer.Chain.Search alias Phoenix.View + @min_query_length 3 + + def search_results(conn, %{"q" => query, "type" => "JSON"}) when byte_size(query) < @min_query_length do + json( + conn, + %{ + items: [], + next_page_path: nil + } + ) + end + def search_results(conn, %{"q" => query, "type" => "JSON"} = params) do [paging_options: paging_options] = paging_options(params) offset = (max(paging_options.page_number, 1) - 1) * paging_options.page_size