kotserubas

kotserubas

Prevent Dataloader from loading association that is already in memory after graphql mutation

Hi All,

I have these objects in graphql scheme:

  import Absinthe.Resolution.Helpers

  object :user do
    field :uuid, :id
    field :email, non_null(:string)
  end

  object :asset do
    field :uuid, :id
    field :name, non_null(:string)
    field :user, non_null(:user) do
      resolve dataloader(Auth, :user)
    end
  end

  def context(ctx) do
    loader =
      Dataloader.new
      |> Dataloader.add_source(Auth, Auth.dataloader_source())

    Map.put(ctx, :loader, loader)
  end

  def plugins do
    [Absinthe.Middleware.Dataloader] ++ Absinthe.Plugin.defaults()
  end

where Auth is Phoenix context:

defmodule App.Auth do
  @moduledoc """
  The Auth context.
  """

  import Ecto.Query, warn: false

  def dataloader_source() do
    Dataloader.Ecto.new(Repo, query: &query/2)
  end

  def query(queryable, _params) do
    queryable
  end

  ...

And this mutation:

  field :create_asset, type: :asset do
    arg :name, non_null(:string)

    resolve &Resolvers.create_asset/3
  end

And these resolver functions:

  def create_asset(_parent, args, %{context: %{current_user: user}}) do
    case Accounting.create_asset(Map.put(args, :user, user)) do
      {:ok, asset} -> {:ok, asset}
      {:error, %Ecto.Changeset{} = cs} ->
        {:error, message: Helpers.format_changeset_errors(cs)}
    end
  end
  def create_asset(_parent, _args, _context) do
    {:error, "not authorized"}
  end

Accounting.create_asset is something like:

  def create_asset(attrs \\ %{}) do
    %Asset{}
    |> ...
    |> put_assoc(:user, attrs.user)
    |> Repo.insert()
  end

So Accounting.create_asset accepts user structure instead of user_id.
That means at the moment asset is successfully created asset.user
is loaded (meta: #Ecto.Schema.Metadata<:loaded, “users”>,).

But when graphql server is processing mutation like:

mutation createAsset {
  createAsset (name: "foobar") {
    uuid
    name
    user {
      email
      uuid
    }
  }
}

three database query is executed:

  1. get current user from auth token. -> ok
  2. insert asset. -> ok
  3. get asset user (to resolve field user in mutation). -> ?

I suppose the last query should not be executed, becase at the time
user field is resolved it’s already loaded to parent (asset) structire.

I tried this approach.

Instead of:

  object :asset do
    field :uuid, :id
    field :name, non_null(:string)
    field :user, non_null(:user) do
      resolve dataloader(Auth, :user)
      # resolve &Resolvers.get_related_user/3
    end
  end

I do (change resolver function to custom one):

  object :asset do
    field :uuid, :id
    field :name, non_null(:string)
    field :user, non_null(:user) do
      resolve &Resolvers.get_related_user/3
    end
  end

where Resolvers.get_related_user/3 is:

  def get_related_user(parent, args, context) do
    case parent.user do
      %Ecto.Association.NotLoaded{} ->
        dataloader(Auth, :user).(parent, args, context)
      _ ->
        {:ok, parent.user}
    end
  end

It works. Now there is only 2 db requests. But I believe it’s ugly approach and there is definitely some nicer way to let Dataloader know that user object is already loaded.

Can you please give an advice?

Most Liked

axelson

axelson

Scenic Core Team

Your Resolvers.get_related_user/3 makes sense to me. Although it might make sense not to call the dataloader helper from it, but instead use Dataloader directly. If you want you could even wrap it up into a helper function.

hisa

hisa

Hi,

I just ran into a similar problem, came into this post and then asked for help in #absinthe-graphql Slack channel, referencing this post.

Luckily and quickly @dpehrson suggested me to avoid calling preload inside my context and leave all the assocs work to dataloader.

I hope that this approach may work for you as well

kotserubas

kotserubas

@axelson, thanks for response.

It seems strange to me that even in this simple example Dataloader doesn’t provide something out of the box. All it have to do is check where relation (that should be rendered in mutation response) is loaded or not.

In my opinion practicing approach I provided above would lead you to mess - you would need to have these helpers for all of your relations.

I’m pretty new to GraphQL, but for now it seems that there are a lot of problems with control over DB logic.
In REST you control pretty everyting (in terms of DB queries and their number).
Here, in GraphQL, you control much less.
Even my simple example shows that default logic would perform unnecessary DB roundtrips.

Aren’t there any other solutions to this problem?

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New

We're in Beta

About us Mission Statement