Skip to content

Commit

Permalink
Add dataloader/2 function to helpers (#898)
Browse files Browse the repository at this point in the history
Adds a convenience `dataloader/2` function that I've needed a couple of
times. It's useful in cases where the resource can be inferred from the
field name but you still want to pass in extra opts such as `args` or
`callback` to the dataloader function.
  • Loading branch information
maartenvanvliet authored Mar 31, 2020
1 parent 1b48cfc commit 3ecaa4a
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion lib/absinthe/resolution/helpers.ex
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,47 @@ defmodule Absinthe.Resolution.Helpers do
"""
@spec dataloader(Dataloader.source_name()) :: dataloader_key_fun()
def dataloader(source) do
dataloader(source, [])
end

@doc """
Resolve a field with a dataloader source.
This function is not imported by default. To make it available in your module do
```
import Absinthe.Resolution.Helpers
```
Same as `dataloader/3`, but it infers the resource name from the field name. For `opts` see
`dataloader/3` on what options can be passed in.
## Examples
```
object :user do
field :posts, list_of(:post),
resolve: dataloader(Blog, args: %{deleted: false})
field :organization, :organization do
resolve dataloader(Accounts, use_parent: false)
end
field(:account_active, non_null(:boolean), resolve: dataloader(
Accounts, callback: fn account, _parent, _args ->
{:ok, account.active}
end
)
)
end
```
"""
@spec dataloader(Dataloader.source_name(), [dataloader_opt]) :: dataloader_key_fun()
def dataloader(source, opts) when is_list(opts) do
fn parent, args, %{context: %{loader: loader}} = res ->
resource = res.definition.schema_node.identifier
do_dataloader(loader, source, resource, args, parent, [])
do_dataloader(loader, source, resource, args, parent, opts)
end
end

Expand Down

0 comments on commit 3ecaa4a

Please sign in to comment.