Skip to content

feat: support nested filtering in the query parser #366

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

Merged
merged 4 commits into from
May 18, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
25 changes: 15 additions & 10 deletions lib/jsonapi/plugs/query_parser.ex
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,15 @@ defmodule JSONAPI.QueryParser do
opts_filter = Keyword.get(opts, :filter, [])

Enum.reduce(filter, config, fn {key, val}, acc ->
check_filter_validity!(opts_filter, key, config)
%{acc | filter: Keyword.put(acc.filter, String.to_existing_atom(key), val)}
check_filter_allowed!(opts_filter, key, config)

keys = key |> String.split(".") |> Enum.map(&String.to_existing_atom/1)
filter = deep_merge(acc.filter, put_as_tree([], keys, val))
%{acc | filter: filter}
end)
end

defp check_filter_validity!(filters, key, config) do
defp check_filter_allowed!(filters, key, config) do
unless key in filters do
raise InvalidQuery, resource: config.view.type(), param: key, param_type: :filter
end
Expand Down Expand Up @@ -215,7 +218,9 @@ defmodule JSONAPI.QueryParser do
end

defp include_reducer(config, valid_includes, inc, acc) do
check_include_validity!(inc, config)
# if an explicit list of allowed includes was specified, check this include
# against it:
check_include_allowed!(inc, config)

if inc =~ ~r/\w+\.\w+/ do
acc ++ handle_nested_include(inc, valid_includes, config)
Expand All @@ -236,25 +241,25 @@ defmodule JSONAPI.QueryParser do
end
end

defp check_include_validity!(key, %Config{opts: opts, view: view}) do
defp check_include_allowed!(key, %Config{opts: opts, view: view}) do
if opts do
check_include_validity!(key, Keyword.get(opts, :include), view)
check_include_allowed!(key, Keyword.get(opts, :include), view)
end
end

defp check_include_validity!(key, allowed_includes, view) when is_list(allowed_includes) do
defp check_include_allowed!(key, allowed_includes, view) when is_list(allowed_includes) do
unless key in allowed_includes do
raise_invalid_include_query(key, view.type())
end
end

defp check_include_validity!(_key, nil, _view) do
defp check_include_allowed!(_key, nil, _view) do
# all includes are allowed if none are specified in input config
end

@spec handle_nested_include(key :: String.t(), valid_include :: list(), config :: Config.t()) ::
list() | no_return()
def handle_nested_include(key, valid_include, config) do
def handle_nested_include(key, valid_includes, config) do
keys =
try do
key
Expand All @@ -267,7 +272,7 @@ defmodule JSONAPI.QueryParser do
last = List.last(keys)
path = Enum.slice(keys, 0, Enum.count(keys) - 1)

if member_of_tree?(keys, valid_include) do
if member_of_tree?(keys, valid_includes) do
put_as_tree([], path, last)
else
raise_invalid_include_query(key, config.view.type())
Expand Down
15 changes: 15 additions & 0 deletions lib/jsonapi/utils/include_tree.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,21 @@ defmodule JSONAPI.Utils.IncludeTree do
Internal utility for building trees of resource relationships
"""

def deep_merge(acc, []), do: acc

def deep_merge(acc, [{key, val} | tail]) do
acc
|> Keyword.update(
key,
val,
fn
[_first | _rest] = old_val -> deep_merge(old_val, val)
old_val -> Keyword.put([], old_val, val)
end
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we need to do some defensive programming here.

    fn
      old_val when is_list(old_val) and is_tuple(hd(old_val)) -> 
        if is_list(val), do: deep_merge(old_val, val), else: val
        
      old_val -> 
        if is_atom(old_val) and is_list(val), do: Keyword.put([], old_val, val), else: val
    end

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I've addressed concerns over robustness with my latest commit. Please take a look and let me know what you think.

I've protected the first case by ensuring we have more keyword list to go before deep merging.
I've simplified the second case to always take the new value on conflict or when the remaining value is not a list.

)
|> deep_merge(tail)
end

@spec put_as_tree(term(), term(), term()) :: term()
def put_as_tree(acc, items, val) do
[head | tail] = Enum.reverse(items)
Expand Down
21 changes: 20 additions & 1 deletion test/jsonapi/plugs/query_parser_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,25 @@ defmodule JSONAPI.QueryParserTest do
end
end

test "parse_filter/2 turns filters key/val pairs" do
test "parse_filter/2 returns filters key/val pairs" do
config = struct(Config, opts: [filter: ~w(name)], view: MyView)
filter = parse_filter(config, %{"name" => "jason"}).filter
assert filter[:name] == "jason"
end

test "parse_filter/2 handles nested filters" do
config = struct(Config, opts: [filter: ~w(author.username)], view: MyView)
filter = parse_filter(config, %{"author.username" => "jason"}).filter
assert filter[:author][:username] == "jason"
end

test "parse_filter/2 handles nested filters with overlap" do
config = struct(Config, opts: [filter: ~w(author.username author.id)], view: MyView)
filter = parse_filter(config, %{"author.username" => "jason", "author.id" => "123"}).filter
assert filter[:author][:username] == "jason"
assert filter[:author][:id] == "123"
end
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about whether Config could come with a filter other than [] but it doesn't look like it


test "parse_filter/2 raises on invalid filters" do
config = struct(Config, opts: [], view: MyView)

Expand All @@ -89,6 +102,12 @@ defmodule JSONAPI.QueryParserTest do
assert parse_include(config, "").include == []
end

test "parse_include/2 succeds given valid nested include specified in allowed list" do
config = struct(Config, view: MyView, opts: [include: ~w(comments.user)])

assert parse_include(config, "comments.user").include == [comments: :user]
end

test "parse_include/2 errors with invalid includes" do
config = struct(Config, view: MyView)

Expand Down