Absinthe context exists to provide shared values to a given document execution.
A common use would be to pass in the current user of a given request. The context
is set at the call to Absinthe.run, and cannot be modified over the course of
a given execution.
As a basic example let’s think about a profile page, where we want the current user
to be able to access basic information about themselves, but not other users.
First we’ll need a very basic schema
A query we might want would look like
If we’re signed in as user 1, we should get only user 1’s email.
In order to set the context, our call to Absinthe.run should look like:
To access this, we need to update our query’s resolve function:
And now it works!
Context and Plugs
When using Absinthe.Plug you don’t have direct access to the Absinthe.run call.
Instead, we can use Plug.Conn.put_private/3 to set context values which Absinthe.Plug
will pass it along to Absinthe.run.
Setting up your GraphQL context is as simple as writing a plug that inserts the
appropriate values into the connection.
Let’s use this mechanism to set our current_user from the previous example via
an authentication header. We will use the same Schema as before.
First, our plug. We’ll be checking the for the authorization header, and calling
out to some unspecified authentication mechanism.
This plug will use the authorization header to lookup the current user, and return
various error codes should that fail. If it succeeds, it correctly sets the absinthe context.
Using this plug is very simple. If we’re just in a normal plug context we can just
make sure it’s plugged prior to Absinthe.Plug
If you’re using a phoenix router, add the context plug to a pipeline.