Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question, best way to decorate with preloaded relations #10

Open
acabreragnz opened this issue Jul 10, 2018 · 1 comment
Open

Question, best way to decorate with preloaded relations #10

acabreragnz opened this issue Jul 10, 2018 · 1 comment

Comments

@acabreragnz
Copy link

acabreragnz commented Jul 10, 2018

Hi all, thank you for the hard work. I have a question.

Suppose that I have a decorated field in the Post schema, but then I do something like

def preload(users_query, preloads) do
   Users
   |> Repo.all()
   |> Repo.preload(preloads)
end

where preloads is dynamic, and could be i.e. [:posts, :comments, :likes, ...]

Which is the correct way to work in cases where you preload the relations, and those relations have decorated fields?

Thank you!

@rsierra
Copy link
Collaborator

rsierra commented Jul 10, 2018

At the moment, I just can think in decorate each relation by hand. Somethig like this:

def preload(users_query, preloads) do
   users_query
   |> Repo.all()
   |> Repo.preload(preloads)
   |> Enum.map(&decorate_preloads(&1, preloads))
end

defp decorate_preloads(struct, preloads) do
   Enum.reduce(preloads, struct, , fn(preload, struct) -> decorate_preload(struct, preload) end)
end

defp decorate_preload(struct, preload) do
   Map.put(struct, preload, do_decorate_preload(Map.get(preload)))
end

# If the preload is a list, decorate each element
defp do_decorate_preload(preloads) when is_list(preloads) do
  Enum.map(preloads, &do_decorate_preload/1)
end

# If custom decorations are needed
defp do_decorate_preload(%Post{} = post) do
  Decoratex.decorate(post, except: :comments_count)
end

# Default decorations
defp do_decorate_preload(preload) do
  Decoratex.decorate(preload)
end

But you will need more pattern matching and complexity if you use keyword lists for nested preloads.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants