Skip to content
This repository was archived by the owner on Jul 25, 2024. It is now read-only.

Commit 43bccc0

Browse files
mynameisrufusJosh Price
authored and
Josh Price
committed
Resolve can return value or raise, or use tuples (#112)
In your resolve function you can now return a tuple with {:ok, result} or {:error, message}. Returning the result and raising works as before.
1 parent 50755c5 commit 43bccc0

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

lib/graphql/execution/resolvable.ex

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@ end
88
defmodule GraphQL.Execution.ResolveWrapper do
99
def wrap(fun) do
1010
try do
11-
{:ok, fun.()}
11+
case fun.() do
12+
{:ok, result} -> {:ok, result}
13+
{:error, message} -> {:error, message}
14+
result -> {:ok, result}
15+
end
1216
rescue
1317
e in RuntimeError -> {:error, e.message}
1418
_ in FunctionClauseError -> {:error, "Could not find a resolve function for this query."}

test/graphql/execution/executor_test.exs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,37 @@ defmodule GraphQL.Execution.Executor.ExecutorTest do
245245
assert_data(result, %{b: "B"})
246246
end
247247

248+
test "resolvers can return value or raise error, or :ok/:error tuples" do
249+
schema = Schema.new(%{
250+
query: %ObjectType{
251+
name: "Q",
252+
fields: %{
253+
a: %{
254+
type: %String{},
255+
resolve: fn(_) -> "A" end
256+
},
257+
b: %{
258+
type: %String{},
259+
resolve: fn(_) -> {:ok, "B"} end
260+
},
261+
c: %{
262+
type: %String{},
263+
resolve: fn(_) -> raise "C" end
264+
},
265+
d: %{
266+
type: %String{},
267+
resolve: fn(_) -> {:error, "D"} end
268+
}
269+
}
270+
}
271+
})
272+
273+
{:ok, result} = execute(schema,~S[query Q { a b c d }])
274+
assert_data(result, %{a: "A", b: "B", c: nil, d: nil})
275+
assert_has_error(result, %{message: "C"})
276+
assert_has_error(result, %{message: "D"})
277+
end
278+
248279
test "lists of things" do
249280
book = %ObjectType{
250281
name: "Book",

0 commit comments

Comments
 (0)