Execution Context

Learn how to integrate context information with the processing of GraphQL requests.

Using the execution context

Now that we have a way to identify users, we need to figure out a way to integrate this information with the processing of GraphQL requests. This integration is necessary so that fields that need to be secured have access to the relevant data.

One option is to make each field resolution function responsible for authenticating the user and passing the token as an argument, but this causes two problems. If we need this information in several fields, we require the user to pass the token in many places. This is not a convenient API for clients. It wouldn’t be very nice for the server either. The server would need to look up the same user in each field even though the returned information would be the same each time.

The Absinthe feature that addresses this problem is called the execution context. It’s a place where we can set values that will be available to all of our resolvers.

Press + to interact
defmodule ContextExample.Schema do
use Absinthe.Schema
query do
field :greeting, :string do
resolve fn _, _, %{context: context} ->
{:ok, "Welcome # {context.current_user.name}"}
end
end
end
end
# Our document
doc = "{ greeting }"
# Our context
context = %{current_user: %{name: "Alicia"}}
# Running Absinthe manually
Absinthe.run(doc, ContextExample.Schema, context: context)

If you paste this into iex -S mix, you’ll see this result:

{:ok, %{data: %{"greeting" => "Welcome Alicia"}}}

The context you passed into the Absinthe.run/3 call is the same context you access in the third argument to the resolution function of the greeting field. After that, you’re just accessing the values you placed inside it ...