Is there anyway to cache data between object field resolvers?

Let’s say I have a user like this

object :user do
  field :num_published_posts, :integer, resolve: &some_func1/3
  field :num_unpublished_posts, :integer, resolve: &some_func2/3
end

def some_func1(_,%{source: user}) do
  get_all_user_posts(user)
  |> sum_published_posts
end

def some_func2(_, %{source: user}) do
  get_all_user_posts(user)
  |> sum_unpublished_posts
end

Here we fetch all the user’s posts twice. Is there any way to cache that DB call, so that the whichever function gets called second, doesn’t need to fetch the data again?

1 Like

Yes, it is possible using dataloader, but in your case I would rather hit 2 separate queries to calculate published/unpublished posts on DB level (without fetching all users to elixir side).

1 Like