Skip to content

Commit

Permalink
feat(ex/detours): add add_author?/2 function and replace with_author
Browse files Browse the repository at this point in the history
  • Loading branch information
firestack committed Jan 31, 2025
1 parent 130dc79 commit 373a6b8
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
20 changes: 20 additions & 0 deletions lib/skate/detours/db/detour.ex
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ defmodule Skate.Detours.Db.Detour do
%{virtual_fields: wanted_virtual_fields, fields: wanted_fields} = split_fields(fields)

query
|> add_author?(wanted_fields)
|> select_merge(^wanted_fields)
|> select_virtual_fields(wanted_virtual_fields)
end
Expand Down Expand Up @@ -106,6 +107,25 @@ defmodule Skate.Detours.Db.Detour do
order_by(query, desc: :updated_at)
end

defp add_author?(query, fields) do
if Keyword.has_key?(fields, :author) do
with_author(query)
else
query
end
end

@doc """
Joins the `Skate.Settings.Db.User` struct into the `Skate.Detours.Db.Detour`
via Ecto preload.
> ### Primary Keys required in query when using `with_author/1` {:.warning}
> When preloading structs, Ecto requires that primary key fields are also
> queried on all preloaded structs.
> This means that when querying `:author` via `select_fields`, you need to
> explicitly request `:id` on both the `Skate.Detours.Db.Detour` and the
> `Skate.Settings.Db.User`.
"""
def with_author(query \\ base()) do
from([detour: d] in query,
join: a in assoc(d, :author),
Expand Down
1 change: 0 additions & 1 deletion lib/skate/detours/detours.ex
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ defmodule Skate.Detours.Detours do

def list_detours(fields) do
Skate.Detours.Db.Detour.Queries.select_fields(fields)
|> Skate.Detours.Db.Detour.Queries.with_author()
|> Skate.Detours.Db.Detour.Queries.sorted_by_last_updated()
|> Repo.all()
end
Expand Down

0 comments on commit 373a6b8

Please sign in to comment.