Absinthe.Plug (absinthe_plug v1.5.8) View Source

A plug for using Absinthe (GraphQL).

Usage

In your router:

plug Plug.Parsers,
  parsers: [:urlencoded, :multipart, :json, Absinthe.Plug.Parser],
  pass: ["*/*"],
  json_decoder: Jason

plug Absinthe.Plug,
  schema: MyAppWeb.Schema

If you want only Absinthe.Plug to serve a particular route, configure your router like:

plug Plug.Parsers,
  parsers: [:urlencoded, :multipart, :json, Absinthe.Plug.Parser],
  pass: ["*/*"],
  json_decoder: Jason

forward "/api",
  to: Absinthe.Plug,
  init_opts: [schema: MyAppWeb.Schema]

See the documentation on Absinthe.Plug.init/1 and the Absinthe.Plug.opts type for information on the available options.

To add support for a GraphiQL interface, add a configuration for Absinthe.Plug.GraphiQL:

forward "/graphiql",
  to: Absinthe.Plug.GraphiQL,
  init_opts: [schema: MyAppWeb.Schema]

For more information, see the API documentation for Absinthe.Plug.

Phoenix.Router

If you are using Phoenix.Router, forward expects different arguments:

Plug.Router

forward "/graphiql",
  to: Absinthe.Plug.GraphiQL,
  init_opts: [
    schema: MyAppWeb.Schema,
    interface: :simple
  ]

Phoenix.Router

forward "/graphiql",
  Absinthe.Plug.GraphiQL,
   schema: MyAppWeb.Schema,
   interface: :simple

For more information see Phoenix.Router.forward/4.

Before Send

If you need to set a value (like a cookie) on the connection after resolution but before values are sent to the client, use the :before_send option:

plug Absinthe.Plug,
  schema: MyApp.Schema,
  before_send: {__MODULE__, :absinthe_before_send}

def absinthe_before_send(conn, %Absinthe.Blueprint{} = blueprint) do
  if auth_token = blueprint.execution.context[:auth_token] do
    put_session(conn, :auth_token, auth_token)
  else
    conn
  end
end
def absinthe_before_send(conn, _) do
  conn
end

The auth_token can be placed in the context by using middleware after your mutation resolve:

# mutation resolver
resolve fn args, _ ->
  case authenticate(args) do
    {:ok, token} -> {:ok, %{token: token}}
    error -> error
  end
end
# middleware afterward
middleware fn resolution, _ ->
  with %{value: %{token: token}} <- resolution do
    Map.update!(resolution, :context, fn ctx ->
      Map.put(ctx, :auth_token, token)
    end)
  end
end

Included GraphQL Types

This package includes additional types for use in Absinthe GraphQL schema and type modules.

See the documentation on Absinthe.Plug.Types for more information.

More Information

For more on configuring Absinthe.Plug and how GraphQL requests are made, see the guide at http://absinthe-graphql.org.

Link to this section Summary

Types

  • :adapter -- (Optional) Absinthe adapter to use (default: Absinthe.Adapter.LanguageConventions).
  • :context -- (Optional) Initial value for the Absinthe context, available to resolvers. (default: %{}).
  • :no_query_message -- (Optional) Message to return to the client if no query is provided (default: "No query document supplied").
  • :json_codec -- (Optional) A module or {module, Keyword.t} dictating which JSON codec should be used (default: Jason). The codec module should implement encode!/2 (e.g., module.encode!(body, opts)).
  • :pipeline -- (Optional) {module, atom} reference to a 2-arity function that will be called to generate the processing pipeline. (default: {Absinthe.Plug, :default_pipeline}).
  • :document_providers -- (Optional) A {module, atom} reference to a 1-arity function that will be called to determine the document providers that will be used to process the request. (default: {Absinthe.Plug, :default_document_providers}, which configures Absinthe.Plug.DocumentProvider.Default as the lone document provider). A simple list of document providers can also be given. See Absinthe.Plug.DocumentProvider for more information about document providers, their role in procesing requests, and how you can define and configure your own.
  • :schema -- (Required, if not handled by Mix.Config) The Absinthe schema to use. If a module name is not provided, Application.get_env(:absinthe, :schema) will be attempt to find one.
  • :serializer -- (Optional) Similar to :json_codec but allows the use of serialization formats other than JSON, like MessagePack or Erlang Term Format. Defaults to whatever is set in :json_codec.
  • :content_type -- (Optional) The content type of the response. Should probably be set if :serializer option is used. Defaults to "application/json".
  • :before_send -- (Optional) Set a value(s) on the connection after resolution but before values are sent to the client.
  • :log_level -- (Optional) Set the logger level for Absinthe Logger. Defaults to :debug.
  • :pubsub -- (Optional) Pub Sub module for Subscriptions.
  • :analyze_complexity -- (Optional) Set whether to calculate the complexity of incoming GraphQL queries.
  • :max_complexity -- (Optional) Set the maximum allowed complexity of the GraphQL query. If a document’s calculated complexity exceeds the maximum, resolution will be skipped and an error will be returned in the result detailing the calculated and maximum complexities.
  • :transport_batch_payload_key -- (Optional) Set whether or not to nest Transport Batch request results in a payload key. Older clients expected this key to be present, but newer clients have dropped this pattern. (default: true)

Functions

Adds key-value pairs into Absinthe context.

Same as assign_context/2 except one key-value pair is assigned.

Parses, validates, resolves, and executes the given Graphql Document

The default list of document providers that are enabled.

The default pipeline used to process GraphQL documents.

Serve an Absinthe GraphQL schema with the specified options.

Sets the options for a given GraphQL document execution.

Link to this section Types

Specs

function_name() :: atom()

Specs

opts() :: [
  schema: module(),
  adapter: module(),
  context: map(),
  json_codec: module() | {module(), Keyword.t()},
  pipeline: {module(), atom()},
  no_query_message: String.t(),
  document_providers:
    [Absinthe.Plug.DocumentProvider.t(), ...]
    | Absinthe.Plug.DocumentProvider.t()
    | {module(), atom()},
  analyze_complexity: boolean(),
  max_complexity: non_neg_integer() | :infinity,
  serializer: module() | {module(), Keyword.t()},
  content_type: String.t(),
  before_send: {module(), atom()},
  log_level: Logger.level(),
  pubsub: module() | nil,
  transport_batch_payload_key: boolean()
]
  • :adapter -- (Optional) Absinthe adapter to use (default: Absinthe.Adapter.LanguageConventions).
  • :context -- (Optional) Initial value for the Absinthe context, available to resolvers. (default: %{}).
  • :no_query_message -- (Optional) Message to return to the client if no query is provided (default: "No query document supplied").
  • :json_codec -- (Optional) A module or {module, Keyword.t} dictating which JSON codec should be used (default: Jason). The codec module should implement encode!/2 (e.g., module.encode!(body, opts)).
  • :pipeline -- (Optional) {module, atom} reference to a 2-arity function that will be called to generate the processing pipeline. (default: {Absinthe.Plug, :default_pipeline}).
  • :document_providers -- (Optional) A {module, atom} reference to a 1-arity function that will be called to determine the document providers that will be used to process the request. (default: {Absinthe.Plug, :default_document_providers}, which configures Absinthe.Plug.DocumentProvider.Default as the lone document provider). A simple list of document providers can also be given. See Absinthe.Plug.DocumentProvider for more information about document providers, their role in procesing requests, and how you can define and configure your own.
  • :schema -- (Required, if not handled by Mix.Config) The Absinthe schema to use. If a module name is not provided, Application.get_env(:absinthe, :schema) will be attempt to find one.
  • :serializer -- (Optional) Similar to :json_codec but allows the use of serialization formats other than JSON, like MessagePack or Erlang Term Format. Defaults to whatever is set in :json_codec.
  • :content_type -- (Optional) The content type of the response. Should probably be set if :serializer option is used. Defaults to "application/json".
  • :before_send -- (Optional) Set a value(s) on the connection after resolution but before values are sent to the client.
  • :log_level -- (Optional) Set the logger level for Absinthe Logger. Defaults to :debug.
  • :pubsub -- (Optional) Pub Sub module for Subscriptions.
  • :analyze_complexity -- (Optional) Set whether to calculate the complexity of incoming GraphQL queries.
  • :max_complexity -- (Optional) Set the maximum allowed complexity of the GraphQL query. If a document’s calculated complexity exceeds the maximum, resolution will be skipped and an error will be returned in the result detailing the calculated and maximum complexities.
  • :transport_batch_payload_key -- (Optional) Set whether or not to nest Transport Batch request results in a payload key. Older clients expected this key to be present, but newer clients have dropped this pattern. (default: true)

Link to this section Functions

Link to this function

assign_context(conn, assigns)

View Source

Specs

assign_context(Plug.Conn.t(), Keyword.t() | map()) :: Plug.Conn.t()

Adds key-value pairs into Absinthe context.

Examples

iex> Absinthe.Plug.assign_context(conn, current_user: user)
%Plug.Conn{}
Link to this function

assign_context(conn, key, value)

View Source

Specs

assign_context(Plug.Conn.t(), atom(), any()) :: Plug.Conn.t()

Same as assign_context/2 except one key-value pair is assigned.

Specs

call(Plug.Conn.t(), map()) :: Plug.Conn.t() | no_return()

Parses, validates, resolves, and executes the given Graphql Document

Link to this function

default_document_providers(_)

View Source

Specs

default_document_providers(map()) :: [Absinthe.Plug.DocumentProvider.t()]

The default list of document providers that are enabled.

This consists of a single document provider, Absinthe.Plug.DocumentProvider.Default, which supports ad hoc GraphQL documents provided directly within the request.

For more information about document providers, see Absinthe.Plug.DocumentProvider.

Link to this function

default_pipeline(config, pipeline_opts)

View Source

Specs

default_pipeline(map(), Keyword.t()) :: Absinthe.Pipeline.t()

The default pipeline used to process GraphQL documents.

This consists of Absinthe's default pipeline (as returned by Absinthe.Pipeline.for_document/1), with the Absinthe.Plug.Validation.HTTPMethod phase inserted to ensure that the correct HTTP verb is being used for the GraphQL operation type.

Specs

init(opts :: opts()) :: Plug.opts()

Serve an Absinthe GraphQL schema with the specified options.

Options

See the documentation for the Absinthe.Plug.opts type for details on the available options.

Specs

put_options(Plug.Conn.t(), Keyword.t()) :: Plug.Conn.t()

Sets the options for a given GraphQL document execution.

Examples

iex> Absinthe.Plug.put_options(conn, context: %{current_user: user})
%Plug.Conn{}
Link to this function

subscribe(conn, topic, config)

View Source
Link to this function

subscribe_loop(conn, topic, config)

View Source