Skip to content

Commit

Permalink
Add feature flag to toggle autocomplete
Browse files Browse the repository at this point in the history
This adds a feature flag to disable autocomplete in case of unforeseen
problems by returning an empty set of completion results in the
response.

This is controlled by the env var `ENABLE_SEARCH_AUTOCOMPLETE`, and
will allow us to consolidate the logic behind disabling autocomplete in
a single place instead of having it scattered across several apps (as
the component will not render completions if no results are returned).
  • Loading branch information
csutter committed Jan 9, 2025
1 parent b06e327 commit 2ab93a4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
8 changes: 7 additions & 1 deletion app/controllers/autocompletes_controller.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
class AutocompletesController < ApplicationController
def show
render json: DiscoveryEngine::Autocomplete::Complete.new(query).completion_result
render json: completion_result
end

private

def completion_result
return CompletionResult.new(suggestions: []) unless Rails.configuration.enable_autocomplete

DiscoveryEngine::Autocomplete::Complete.new(query).completion_result
end

def query
params[:q]
end
Expand Down
6 changes: 6 additions & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,11 @@ class Application < Rails::Application
## currently only using a single instance (the Publishing "shared" Redis). If we ever need to
## use multiple Redis instances, this is the only place that needs updating.
config.redlock_redis_instances = [config.redis_url]

# Feature flags
def self.feature_flag(name, default: false)
ActiveModel::Type::Boolean.new.cast(ENV.fetch(name, default))
end
config.enable_autocomplete = feature_flag("GOVUK_SEARCH_ENABLE_AUTOCOMPLETE", default: true)
end
end
15 changes: 15 additions & 0 deletions spec/requests/autocomplete_request_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,19 @@
})
end
end

context "when autocomplete is disabled through the feature flag" do
before do
allow(Rails.configuration).to receive(:enable_autocomplete).and_return(false)
end

it "returns empty suggestions" do
get "/autocomplete.json?q=foo"

expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to eq({
"suggestions" => [],
})
end
end
end

0 comments on commit 2ab93a4

Please sign in to comment.