Refactor get_artikel*() functions/sql

This commit is contained in:
Thelonius Kort
2023-02-28 21:42:05 +01:00
parent fc0818678c
commit b87b54ec71
3 changed files with 27 additions and 12 deletions

View File

@ -4,6 +4,8 @@ defmodule Outlook.Artikel do
"""
alias Outlook.Translations.Translation
alias Outlook.Articles.Article
alias Outlook.Authors.Author
import Ecto.Query, warn: false
alias Outlook.Repo
@ -15,8 +17,24 @@ defmodule Outlook.Artikel do
def get_artikel!(artikel) when is_struct(artikel), do: get_artikel!(artikel.id)
def get_artikel!(id) do
Repo.one(from t in Translation, where: t.id == ^id and t.public == true)
|> Repo.preload([article: :author])
q = from t in Translation,
join: a in Article, on: t.article_id == a.id,
join: au in Author, on: a.author_id == au.id,
select: [
title: t.title,
date: t.date,
public_content: t.public_content,
title_org: a.title,
url_org: a.url,
date_org: a.date,
author: au.name,
author_id: au.id
],
where: t.id == ^id and t.public == true
case Repo.one(q) do
nil -> {:error, "Artikel does not exist, or isn't public."}
artikel -> {:ok, artikel |> Enum.into(%{})}
end
end
def get_artikel_by_tid(tid) do
@ -25,9 +43,5 @@ defmodule Outlook.Artikel do
|> List.last()
|> String.to_integer(36)
|> get_artikel!()
case artikel do
%Translation{} -> {:ok, artikel}
_ -> {:error, "Artikel does not exist, or isn't public."}
end
end
end