TypedGql (TypedGql v0.13.0)

Copy Markdown View Source

Compile-time GraphQL client for Elixir.

Validates GraphQL operations at compile time and generates typed Ecto embedded schemas for responses.

Usage

defmodule MyApp.GitHub do
  use TypedGql,
    otp_app: :my_app,
    source: "priv/schemas/github.json"

  defgql :get_user, ~GQL"""
    query($login: String!) {
      user(login: $login) {
        name
      }
    }
  """
end

Options

  • :otp_app (required) — the OTP application for runtime config lookup

  • :source (required) — path to a schema JSON file (relative to the caller file), or an inline JSON string

  • :scalars — custom scalar type mappings (default: %{})

  • :generation_pluginsTypedGql.Generation.Plugin modules that hook into response-type generation. TypedGql's built-in plugins (e.g. @include/@skip handling) always run first; these are appended after them (default: [])

  • :endpoint — default GraphQL endpoint URL. Optional: the URL can also come from :req_options (:url/:base_url) or from prepare_req/1

  • :req_options — default Req options passed directly to Req.new/1 (keyword list). Supports all Req options including middleware/plugins. Common examples:

    • Headers: req_options: [headers: [authorization: "Bearer token"]]
    • Timeouts: req_options: [receive_timeout: 30_000]
    • Plug (for testing): req_options: [plug: {Req.Test, MyApp.GitHub}]

    You can also attach Req plugins via the :req_options key. Plugins are attached by passing the plugin's attach/1 options:

    # In config/runtime.exs
    config :my_app, MyApp.GitHub,
      req_options: [auth: {:bearer, System.fetch_env!("GITHUB_TOKEN")}]
    
    # In test setup
    config :my_app, MyApp.GitHub,
      req_options: [plug: {Req.Test, MyApp.GitHub}]

Summary

Functions

Executes a compiled GraphQL query.

Functions

execute(query, variables \\ %{}, opts \\ [])

@spec execute(TypedGql.Query.t(), struct() | map(), keyword()) ::
  {:ok, TypedGql.Result.t()} | {:error, Req.Response.t() | Exception.t()}

Executes a compiled GraphQL query.

Takes a %TypedGql.Query{} struct (produced by defgql/defgqlp), the variables, and optional keyword options.

Options override runtime config which overrides compile-time defaults.

Variables given as a struct — one built by the operation's generated Variables.build/1 — are dumped whole, so an optional field the caller never set is sent as null. The generated defgql functions instead prune the dump against the params they were called with, keeping an omitted field absent from the request. Prefer them unless you need to execute a %TypedGql.Query{} you assembled yourself.