Created
October 15, 2019 21:56
-
-
Save nietaki/6f6c78d79c915c3c2c0273c754bf6561 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def category_preloader(category_names) when is_list(category_names) do | |
# category_names are already deduplicated | |
Enum.map(category_names, &RemoteService.retrieve_category_info/1) | |
end | |
query = | |
from(p in Post, | |
where: p.id in ^post_ids, | |
preload: [category: ^&category_preloader/1] | |
) | |
posts = Repo.all(query) | |
refute Enum.any?(posts, &(&1.category == nil)) | |
# alternatively, concurrent version | |
def concurrent_category_preloader(category_names) when is_list(category_names) do | |
category_names | |
|> Enum.map(fn name -> Task.async(RemoteService, :retrieve_category_info, [name]) end) | |
|> Enum.map(fn task -> Task.await(task) end) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment