Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not raise on unsuccessful cast #156

Merged
merged 5 commits into from
Apr 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions lib/geo_postgis/geometry.ex
Original file line number Diff line number Diff line change
Expand Up @@ -78,19 +78,33 @@ if Code.ensure_loaded?(Ecto.Type) do
def cast(%struct{} = geom) when struct in @geometries, do: {:ok, geom}

def cast(%{"type" => type, "coordinates" => _} = geom) when type in @types do
{:ok, Geo.JSON.decode!(geom)}
do_cast(geom)
end

def cast(%{"type" => "GeometryCollection", "geometries" => _} = geom) do
{:ok, Geo.JSON.decode!(geom)}
do_cast(geom)
end

def cast(geom) when is_binary(geom) do
{:ok, geom |> Geo.PostGIS.Config.json_library().decode!() |> Geo.JSON.decode!()}
do_cast(geom)
end

def cast(_), do: :error

defp do_cast(geom) when is_binary(geom) do
case Geo.PostGIS.Config.json_library().decode(geom) do
{:ok, geom} when is_map(geom) -> do_cast(geom)
{:error, reason} -> {:error, [message: "failed to decode JSON", reason: reason]}
end
end

defp do_cast(geom) do
case Geo.JSON.decode(geom) do
{:ok, result} -> {:ok, result}
{:error, reason} -> {:error, [message: "failed to decode GeoJSON", reason: reason]}
end
end

def embed_as(_), do: :self

def equal?(a, b), do: a == b
Expand Down
Loading