Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eprothro/75a7e84b790227a97084ae38fed0c73d to your computer and use it in GitHub Desktop.
Save eprothro/75a7e84b790227a97084ae38fed0c73d to your computer and use it in GitHub Desktop.

Context: batch queries constructed using data from the context

Currently, dataloader/3 helper accepts only statically defined args.

This means we cannot use the dataloader helper to use data from the Absinthe.Resolution to build the batch key.

We can do this directly:

field :is_favorited, non_null(:boolean),
  description: "Flag indicating if the resource is favorited or not by the current user" do
  resolve(fn resource, _, %{context: %{current_user: user, loader: loader}} ->
    batch_key = {:resource_favorites, %{user: user}}
    loader
    |> Dataloader.load(:rdbms, batch_key, resource)
    |> on_load(fn loader ->
      case Dataloader.get(loader, :rdbms, batch_key, resource) do
        nil -> {:ok, false}
        _resource_favorite -> {:ok, true}
      end
    end)
  end)
end

What if the :args opt also accepted a 3 arity function similar to resolve/3?

field :is_favorited, non_null(:boolean),
  description: "Flag indicating if the resource is favorited or not" do
  resolve(
    dataloader(:rdbms, :resource_favorites,
      args: fn _parent, _args, %{context: %{current_user: user}} ->
        %{user: user}
      end
      callback: fn resource_favorite, _parent, _args ->
        case resource_favorite do
          nil -> {:ok, false}
          _resource_favorite -> {:ok, true}
        end
      end
    )
  )
end

Motivation

With the current implementation, our team reaches for batch instead of dataloader (which is used for all other batch queries) when we need to construct a batch query using data from the context. It would be nice to be able to use the dataloader helper to maintain a single batch query paradigm.

With a feature like above, the dataloader internals (batch key concept, etc) are kept opaque to a developer that is making a schema change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment