Should I separate context queries from special web queries?

PJUllrich
Sat, 09 Oct 2021 11:21:05 +0000
Questions / Help

I am contemplating whether I should separate highly specific queries which only a single controller uses from the more general purpose queries located in the context module. Let me set the picture first:

Let’s say I have a Phoenix project with the following simplified project structure:

lib/
  my_app/
    post_context.ex
  my_app_web/
    post_controller.ex

The PostContext holds the typical general purpose queries like list_posts/0 get_post!/1 update_post/2 and delete_post/1.

The PostController however uses a highly specific query, which is written only for this controller. Something like:

def get_latest_posts_by_top_authors_ranked_by_likes(top_author_ids) do
  from(p in Post,
    where: p.author_id in ^top_author_ids
      and not p.deleted?
      and not p.under_review?
      # only show posts from this year
      and p.published_at > ^~N[2021-01-01],
    order_by: [desc: p.likes]
  )
  |> Repo.all()
end

My point is that this query solves a very specific need by the controller and isn’t used anywhere else. Usually, I would still put this query in the PostContext, because that is where you usually put queries. However, I thought since this query is only used by a single controller and nowhere else, why not put it into the my_app_web folder? This would be the new project structure:

lib/
  my_app/
    post_context.ex
  my_app_web/
    post_controller.ex
    queries/
      get_latest_posts_by_top_authors_ranked_by_likes.ex

What do you think about the new project structure?
Do you think it unacceptably violates the usual phoenix structure and shouldn’t be done?
Do you think all queries, even the special ones, belong in the context module?

6 posts - 3 participants