Skip to content

Instantly share code, notes, and snippets.

@moroz
Created May 14, 2022 15:17
Show Gist options
  • Save moroz/0cccc3871fc3f4ac0f28ba7479ea72e0 to your computer and use it in GitHub Desktop.
Save moroz/0cccc3871fc3f4ac0f28ba7479ea72e0 to your computer and use it in GitHub Desktop.
Absinthe resolve field with batch
defmodule MyAppWeb.Api.Macros do
@moduledoc """
Not actual Absinthe middleware.
"""
use Absinthe.Schema.Notation
@doc """
Macro to reuse the common pattern of preloading associations using
a batch function using `id` as the key.
"""
defmacro resolve_with_batch(module, function, opts \\ []) do
key = Keyword.get(opts, :key, :id)
quote do
resolve(fn parent, _, _ ->
id = Map.get(parent, unquote(key))
batch(
{unquote(module), unquote(function)},
id,
fn batch ->
{:ok, Map.get(batch, id)}
end
)
end)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment