absinthe_ecto v0.1.3 Absinthe.Ecto View Source

Provides some helper functions for easy batching of ecto assocations

These functions all make use of the batch plugin found in Absinthe, they’re merely just some helpful ways to use this plugin in the context of simple ecto associations.

Basic Usage

First specify the repo you’re going to use:

use Absinthe.Ecto, repo: MyApp.Repo

Then, supposing you have some ecto associations as in this example schema:

defmodule MyApp.Post do
  use Ecto.Schema

  schema "posts" do
    belongs_to :author, MyApp.User
    has_many :comments, MyApp.Comment
    field :name, :string
    field :body, :string
  end
end

Your graphql post object might look like:

object :post do
  field :author, :user, resolve: assoc(:author)
  field :comments, list_of(:comment), resolve: assoc(:comments)
  field :title, :string
  field :body, :string
end

Now, queries which get the author or comments of many posts will result in just 1 call to the database for each!

The assoc macro just builds a resolution function which calls ecto_batch/4.

See the ecto_batch/4 function for how to do this from within a regular resolution function.

Link to this section Summary

Functions

This function lets you batch load an item from within a normal resolution function

Link to this section Functions

Link to this macro assoc(association) View Source (macro)

Example:

field :author, :user, resolve: assoc(:author)
Link to this macro assoc(association, query_fun) View Source (macro)

Example:

field :posts, list_of(:post) do
  resolve assoc(:posts, fn posts_query, _args, _context ->
    posts_query |> order_by(asc: :name)
  end)
end
Link to this function assoc(repo, association, query_fun, callback \\ &default_callback/1) View Source

Generally you would use the assoc/1 macro.

However, this can be useful if you need to specify an ecto repo.

field :author, :user, resolve: assoc(MyApp.Repo, :author)
Link to this function ecto_batch(repo, parent, association, callback \\ &default_callback/1) View Source

This function lets you batch load an item from within a normal resolution function.

It also supports a callback which is run after the item is loaded. For belongs to associations this may be nil.

Example

resolve fn post, _, _ ->
  MyApp.Repo |> ecto_batch(post, :author, fn author ->
    # you can do something with the author after its loaded here.
    # note that it may be nil.
    {:ok, author}
  end)
end