2019-03-14 17:31:14 +00:00
|
|
|
defmodule MobilizonWeb.Resolvers.Address do
|
|
|
|
@moduledoc """
|
|
|
|
Handles the comment-related GraphQL calls
|
|
|
|
"""
|
|
|
|
require Logger
|
|
|
|
alias Mobilizon.Addresses
|
2019-03-19 10:16:03 +00:00
|
|
|
alias Mobilizon.Addresses.Address
|
2019-03-14 17:31:14 +00:00
|
|
|
alias Mobilizon.Service.Geospatial
|
|
|
|
|
2019-03-19 10:16:03 +00:00
|
|
|
@doc """
|
|
|
|
Search an address
|
|
|
|
"""
|
|
|
|
@spec search(map(), map(), map()) :: {:ok, list(Address.t())}
|
2019-07-30 08:35:29 +00:00
|
|
|
def search(_parent, %{query: query, page: _page, limit: _limit}, %{context: %{ip: ip}}) do
|
2019-09-22 11:41:24 +00:00
|
|
|
country = ip |> Geolix.lookup() |> Map.get(:country, nil)
|
2019-03-14 17:31:14 +00:00
|
|
|
|
|
|
|
local_addresses = Task.async(fn -> Addresses.search_addresses(query, country: country) end)
|
|
|
|
|
|
|
|
remote_addresses = Task.async(fn -> Geospatial.service().search(query) end)
|
|
|
|
|
|
|
|
addresses = Task.await(local_addresses) ++ Task.await(remote_addresses)
|
|
|
|
|
2019-08-22 13:57:44 +00:00
|
|
|
# If we have results with same origin_id than those locally saved, don't return them
|
|
|
|
addresses =
|
|
|
|
Enum.reduce(addresses, %{}, fn address, addresses ->
|
|
|
|
if Map.has_key?(addresses, address.origin_id) && !is_nil(address.url) do
|
|
|
|
addresses
|
|
|
|
else
|
|
|
|
Map.put(addresses, address.origin_id, address)
|
|
|
|
end
|
|
|
|
end)
|
|
|
|
|
|
|
|
addresses = Map.values(addresses)
|
|
|
|
|
2019-03-14 17:31:14 +00:00
|
|
|
{:ok, addresses}
|
|
|
|
end
|
|
|
|
|
2019-03-19 10:16:03 +00:00
|
|
|
@doc """
|
|
|
|
Reverse geocode some coordinates
|
|
|
|
"""
|
|
|
|
@spec reverse_geocode(map(), map(), map()) :: {:ok, list(Address.t())}
|
2019-03-14 17:31:14 +00:00
|
|
|
def reverse_geocode(_parent, %{longitude: longitude, latitude: latitude}, %{context: %{ip: ip}}) do
|
2019-09-22 11:41:24 +00:00
|
|
|
country = ip |> Geolix.lookup() |> Map.get(:country, nil)
|
2019-03-14 17:31:14 +00:00
|
|
|
|
|
|
|
local_addresses =
|
|
|
|
Task.async(fn -> Addresses.reverse_geocode(longitude, latitude, country: country) end)
|
|
|
|
|
|
|
|
remote_addresses = Task.async(fn -> Geospatial.service().geocode(longitude, latitude) end)
|
|
|
|
|
|
|
|
addresses = Task.await(local_addresses) ++ Task.await(remote_addresses)
|
|
|
|
|
|
|
|
{:ok, addresses}
|
|
|
|
end
|
|
|
|
end
|