GreenFairy.Field.Connection (GreenFairy v0.3.0)

View Source

Connection support for Relay-style pagination.

This module provides macros for defining connections with auto-generated Connection and Edge types.

Usage

type "User", struct: MyApp.User do
  connection :friends, MyApp.GraphQL.Types.User do
    edge do
      field :friendship_date, :datetime
    end
    field :total_count, :integer
  end
end

Summary

Functions

Generates a connection field with auto-generated Connection and Edge types.

Creates a connection result from a list of items.

Creates a connection result from an Ecto query.

Generates the edge and connection object types from stored connection definitions.

Functions

connection(field_name, type_module_or_opts \\ [], list)

(macro)

Generates a connection field with auto-generated Connection and Edge types.

Options

  • :node - The node type identifier (defaults to the type_module's identifier)
  • :resolve - Custom resolver function

from_list(items, args, opts \\ [])

Creates a connection result from a list of items.

Examples

GreenFairy.Field.Connection.from_list(users, args)

Options

  • :cursor_fn - Function to generate cursors (default: index-based)
  • :total_count - Total count of items before pagination (default: length of items before pagination)
  • :deferred - Use deferred loading for totalCount and exists (default: false)

Deferred Loading

When :deferred is true, totalCount and exists are returned as functions that execute only when those fields are requested in the GraphQL query. This avoids expensive COUNT queries when not needed.

from_query(query, repo, args, opts \\ [])

Creates a connection result from an Ecto query.

This function handles cursor-based pagination for Ecto queries.

Options

  • :cursor_fn - Function to generate cursors (default: index-based)
  • :count_query - Custom query for counting (default: uses the same query)
  • :deferred - Use deferred loading for totalCount and exists (default: false)

Deferred Loading

When :deferred is true, the count query is wrapped in a function and only executed when the totalCount or exists field is requested. This significantly improves performance for large datasets when those fields aren't needed.

generate_connection_types(connections)

Generates the edge and connection object types from stored connection definitions.

Called from Type.before_compile to generate types at module top-level.