Created
May 14, 2022 15:17
-
-
Save moroz/0cccc3871fc3f4ac0f28ba7479ea72e0 to your computer and use it in GitHub Desktop.
Absinthe resolve field with batch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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