From 28c79fbaf5ed9f0cb9f7bf0cbe1b4dd33b00bfa3 Mon Sep 17 00:00:00 2001 From: matthew graham Date: Sun, 1 Sep 2024 18:19:33 -0400 Subject: [PATCH] fix path_string crash when path includes list and add documentation for path_string/1 this fix is #1337 https://github.com/absinthe-graphql/absinthe/issues/1337 --- lib/absinthe/resolution.ex | 23 +++++++++++++++++++- test/absinthe/resolution/middleware_test.exs | 8 +++++-- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/lib/absinthe/resolution.ex b/lib/absinthe/resolution.ex index 3d8279036a..fb4e3547a9 100644 --- a/lib/absinthe/resolution.ex +++ b/lib/absinthe/resolution.ex @@ -235,8 +235,29 @@ defmodule Absinthe.Resolution do def call(res, _), do: res + @doc """ + Get a list of strings representing the path to this field resolution. + The index of list items is dropped and the schema type is included. + + ## Examples + Given some query: + ```graphql + query {users { email }} + ``` + + If you called this function inside a resolver on the users email field it + returns a value like: + + ```elixir + resolve fn _, _, resolution -> + Absinthe.Resolution.path(resolution) #=> ["email", "users", "query"] + end + ``` + """ def path_string(%__MODULE__{path: path}) do - Enum.map(path, fn + path + |> Enum.reject(fn x -> is_integer(x) end) + |> Enum.map(fn %{name: name, alias: alias} -> alias || name diff --git a/test/absinthe/resolution/middleware_test.exs b/test/absinthe/resolution/middleware_test.exs index 1d06ea09f9..4276668d81 100644 --- a/test/absinthe/resolution/middleware_test.exs +++ b/test/absinthe/resolution/middleware_test.exs @@ -74,6 +74,10 @@ defmodule Absinthe.MiddlewareTest do field :path, :path do resolve fn _, _ -> {:ok, %{}} end end + + field :list_of_paths, list_of(:path) do + resolve fn _, _ -> {:ok, [%{}]} end + end end object :path do @@ -188,13 +192,13 @@ defmodule Absinthe.MiddlewareTest do test "it gets the path of the current field" do doc = """ - {foo: path { bar: path { result }}} + {foo: listOfPaths { bar: path { result }}} """ assert {:ok, %{data: data}} = Absinthe.run(doc, __MODULE__.Schema, context: %{current_user: %{}}) - assert %{"foo" => %{"bar" => %{"result" => ["result", "bar", "foo", "RootQueryType"]}}} == + assert %{"foo" => [%{"bar" => %{"result" => ["result", "bar", "foo", "RootQueryType"]}}]} == data end end