Refactor query functions

This commit is contained in:
Thelonius Kort
2023-03-02 23:17:21 +01:00
parent cbea9450e4
commit b20bbb232c

View File

@ -8,7 +8,7 @@ implement to_param protocol (no more needed for Outlook.Translations.Translation
alias Outlook.Translations.Translation alias Outlook.Translations.Translation
alias Outlook.Articles.Article alias Outlook.Articles.Article
alias Outlook.Authors.Author alias Outlook.Authors.Author
alias Outlook.Public.Artikel alias Outlook.Public.{Artikel,Autor}
import Ecto.Query, warn: false import Ecto.Query, warn: false
alias Outlook.Repo alias Outlook.Repo
@ -17,19 +17,17 @@ implement to_param protocol (no more needed for Outlook.Translations.Translation
q = from t in Translation, q = from t in Translation,
join: a in Article, on: t.article_id == a.id, join: a in Article, on: t.article_id == a.id,
join: au in Author, on: a.author_id == au.id, join: au in Author, on: a.author_id == au.id,
select: [ select: %Artikel{
title: t.title, title: t.title,
date: t.date, date: t.date,
teaser: t.teaser, teaser: t.teaser,
id: t.id, id: t.id,
date_org: a.date, date_org: a.date,
autor_name: au.name, autor_name: au.name,
], },
where: t.public == true and t.language == ^language, where: t.public == true and t.language == ^language,
order_by: [desc: t.date] order_by: [desc: t.date]
Repo.all(q) Repo.all(q)
# |> Enum.map(fn rec -> Enum.into(rec, %{}) end)
|> Enum.map(fn map -> struct(Artikel, map) end)
end end
def get_artikel!(artikel) when is_struct(artikel), do: get_artikel!(artikel.id) def get_artikel!(artikel) when is_struct(artikel), do: get_artikel!(artikel.id)
@ -37,7 +35,7 @@ implement to_param protocol (no more needed for Outlook.Translations.Translation
q = from t in Translation, q = from t in Translation,
join: a in Article, on: t.article_id == a.id, join: a in Article, on: t.article_id == a.id,
join: au in Author, on: a.author_id == au.id, join: au in Author, on: a.author_id == au.id,
select: [ select: %Artikel{
title: t.title, title: t.title,
date: t.date, date: t.date,
public_content: t.public_content, public_content: t.public_content,
@ -46,11 +44,11 @@ implement to_param protocol (no more needed for Outlook.Translations.Translation
date_org: a.date, date_org: a.date,
autor_name: au.name, autor_name: au.name,
autor_id: au.id autor_id: au.id
], },
where: t.id == ^id and t.public == true where: t.id == ^id and t.public == true
case Repo.one(q) do case Repo.one(q) do
nil -> {:error, "Artikel does not exist, or isn't public."} nil -> {:error, "Artikel does not exist, or isn't public."}
artikel -> {:ok, struct(Artikel, artikel)} artikel -> {:ok, artikel}
end end
end end