Return response fields based on the context using dataloader

Need to return response based on the context.

This is my schema.ex

object(:user) do
    field :name, :string
    field :dob, :string
    field :test_1, dataloader(Repo)
    field :test_2, dataloader(Repo)
    field :test_3, dataloader(Repo)
    field :test_4, dataloader(Repo)
    field :test_5, dataloader(Repo)
end

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

  def context(ctx) do
    loader =
      Dataloader.new()
      |> Dataloader.add_source(Repo, Dataloader.Ecto.new(Repo))
  
    Map.put(ctx, :loader, loader)
end
  1. If the get_user API was hit by logged in user(By context, I was validating that). I will to return all the fields. The dataloader will do loading the associations job for me.
%{
    name: "some name", 
    dob: "some dob", 
    test_1:  "some_test_1", 
    test_2: "some_test_2",
    test_3: "some_test_3",
    test_4: "some_test_4",
    test_5: "some_test_5"
}
  1. If the same get_user API was hit by not logged user(Without token). I only want to return “name” field from the backend.!.
%{
    name: "some name", 
    dob: nil, 
    test_1:  nil, 
    test_2: nil,
    test_3: nil,
    test_4: nil,
    test_5: nil
}

How can i achieve this with dataloader?. Dataloader try to load all the association every time(If that particular field was passed from the frontend)

From the context/1 function you can pass the current user from the ctx variable into the dataloader source, and then use this in your dataloader functions.

See Dataloader.Ecto — dataloader v1.0.8 under default_params

1 Like