Skip to content

Commit

Permalink
Filter location autocomplete results by USA and appropriate states (#…
Browse files Browse the repository at this point in the history
…2127)

* filter results by USA and appropriate states

* test
  • Loading branch information
anthonyshull authored Jul 12, 2024
1 parent 1d75e50 commit 5078e3e
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
17 changes: 17 additions & 0 deletions lib/location_service/location_service.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,18 @@ defmodule LocationService do
@cache Application.compile_env!(:dotcom, :cache)
@ttl :timer.hours(24)

@filter ~r/,\s(MA|NH|RI),\s/

@behaviour LocationService.Behaviour

@bias_options %{
BiasPosition: [-71.0660, 42.3548],
FilterCountries: ["USA"],
MaxResults: 50
}
@bounding_options %{
FilterBBox: [-71.9380, 41.3193, -69.6189, 42.8266],
FilterCountries: ["USA"],
MaxResults: 50
}

Expand All @@ -30,10 +34,23 @@ defmodule LocationService do
def autocomplete(text, limit, options) when 1 <= limit and limit <= 15 do
Request.autocomplete(text, limit, options)
|> Result.handle_response(%{search: text, limit: limit})
|> filter_results()
end

def autocomplete(_, _, _), do: {:error, :invalid_arguments}

defp filter_results({:ok, results}) do
results =
results
|> Enum.filter(fn result ->
Regex.match?(@filter, result.address)
end)

{:ok, results}
end

defp filter_results(result), do: result

@decorate cacheable(cache: @cache, on_error: :nothing, opts: [ttl: @ttl])
def geocode(address, options \\ @bounding_options) when is_binary(address) do
Request.new(address, options)
Expand Down
36 changes: 34 additions & 2 deletions test/location_service/location_service_test.exs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
defmodule LocationServiceTest do
use ExUnit.Case, async: true

import LocationService
import Mox

Expand Down Expand Up @@ -104,7 +105,7 @@ defmodule LocationServiceTest do
%{
"Results" => [
%{
"Text" => "Test Location"
"Text" => "Test Location, MA, "
}
]
}
Expand All @@ -114,7 +115,7 @@ defmodule LocationServiceTest do

assert {:ok, result} = autocomplete("Tes", 2)

assert [%LocationService.Suggestion{address: "Test Location"}] = result
assert [%LocationService.Suggestion{address: "Test Location, MA, "}] = result
end

test "can parse a response with error" do
Expand All @@ -124,5 +125,36 @@ defmodule LocationServiceTest do

assert {:error, :internal_error} = autocomplete("test", 2)
end

test "filters by states" do
expect(ExAws.Mock, :request, fn _ ->
{:ok,
%{
status_code: 200,
body:
%{
"Results" => [
%{
"Text" => "Test Location, MA, "
},
%{
"Text" => "Test Location, NH, "
},
%{
"Text" => "Test Location, RI, "
},
%{
"Text" => "Test Location, VT, "
}
]
}
|> Jason.encode!()
}}
end)

{:ok, results} = autocomplete("Test Location", 4)

assert Kernel.length(results) == 3
end
end
end

0 comments on commit 5078e3e

Please sign in to comment.