Skip to content
Merged
Show file tree
Hide file tree
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
11 changes: 9 additions & 2 deletions lib/jsonpatch/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -300,12 +300,19 @@ defmodule Jsonpatch.Utils do
end

defp find_destination(target, path, [fragment | tail], opts) when is_list(target) do
with {:ok, index} <- cast_fragment(fragment, path, target, opts) do
val = Enum.fetch!(target, index)
with {:ok, index} <- cast_fragment(fragment, path, target, opts),
{:ok, val} <- fetch(target, index) do
find_destination(val, path ++ [fragment], tail, opts)
else
{:error, :invalid_path} -> {:error, {:invalid_path, path ++ [fragment]}}
{:error, _} = error -> error
end
end

defp find_destination(_target, path, [fragment | _tail], _opts) do
{:error, {:invalid_path, path ++ [fragment]}}
end

defp do_update_destination(_target, value, _path, :root, _opts) do
{:ok, value}
end
Expand Down
30 changes: 30 additions & 0 deletions test/jsonpatch_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,36 @@ defmodule JsonpatchTest do
Jsonpatch.apply_patch(patch, target)
end

test "Return an error when the path goes through a scalar or a missing list element" do
target = %{"name" => "Bob", "age" => nil, "hobbies" => [%{"x" => 1}]}

paths = [
{"/name/first", ["name", "first"]},
{"/age/years/min", ["age", "years"]},
{"/hobbies/0/x/y", ["hobbies", "0", "x", "y"]},
{"/hobbies/1/x", ["hobbies", "1"]},
{"/hobbies/-/x", ["hobbies", "-"]}
]

for {path, fragments} <- paths,
patch <- [
%{"op" => "add", "path" => path, "value" => 1},
%{"op" => "test", "path" => path, "value" => 1},
%{"op" => "copy", "from" => path, "path" => "/new"},
%{"op" => "move", "from" => path, "path" => "/new"},
%{"op" => "copy", "from" => "/name", "path" => path}
] do
assert {:error,
%Jsonpatch.Error{
patch: ^patch,
patch_index: 0,
reason: {:invalid_path, ^fragments}
}} = Jsonpatch.apply_patch(patch, target)

assert {:ok, ^target} = Jsonpatch.apply_patch(patch, target, ignore_invalid_paths: true)
end
end

test "Apply patch with multiple operations with binary keys" do
patch = [
%Jsonpatch.Operation.Remove{path: "/age"},
Expand Down
Loading