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

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
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
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
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New

We're in Beta

About us Mission Statement