Add embedded schema for Artikel

This commit is contained in:
Thelonius Kort
2023-02-28 23:38:56 +01:00
parent ed98f4cbc4
commit 02e6340c0a
6 changed files with 114 additions and 7 deletions

64
lib/outlook/public.ex Normal file
View File

@ -0,0 +1,64 @@
defmodule Outlook.Public do
@moduledoc """
This should replace Outlook.Artikel and Outlook.Autoren for
both of which embedded schemas should be created, for Artikel the schema should
implement to_param protocol (no more needed for Outlook.Translations.Translation then).
"""
alias Outlook.Translations.Translation
alias Outlook.Articles.Article
alias Outlook.Authors.Author
alias Outlook.Public.Artikel
import Ecto.Query, warn: false
alias Outlook.Repo
def list_artikel(language \\ "DE") do
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,
teaser: t.teaser,
id: t.id,
date_org: a.date,
autor_name: au.name,
],
where: t.public == true and t.language == ^language,
order_by: [desc: t.date]
Repo.all(q)
|> Enum.map(fn rec -> Enum.into(rec, %{}) end)
|> Enum.map(fn map -> struct(Artikel, map) end)
end
def get_artikel!(artikel) when is_struct(artikel), do: get_artikel!(artikel.id)
def get_artikel!(id) do
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, struct(Artikel, artikel |> Enum.into(%{}))}
end
end
def get_artikel_by_tid(tid) do
tid
|> String.split(~r/--(?=[0-9A-Za-z])/)
|> List.last()
|> String.to_integer(36)
|> get_artikel!()
end
end

View File

@ -0,0 +1,43 @@
defmodule Outlook.Public.Artikel do
use Ecto.Schema
alias Outlook.Public.Artikel
embedded_schema do
field :title, :string
field :date, :utc_datetime
field :public_content, :string
field :title_org, :string
field :url_org, :string
field :date_org, :utc_datetime
field :autor_name, :string
field :author_id, :integer
field :teaser, :string
# field :autor, Autor
end
def translate_unicode(str) do
mapping = %{"Ä" => "Ae",
"Ö" => "Oe",
"Ü" => "Ue",
"ä" => "ae",
"ö" => "oe",
"ü" => "ue",
"ß" => "ss"}
{:ok, re} = "[#{Map.keys(mapping) |> Enum.join}]" |> Regex.compile("u")
Regex.replace(re, str, fn(c) -> mapping[c] end)
end
def spit_title(title) do
title
|> translate_unicode()
|> String.replace(~r/[^\w\s-]/u, "")
|> String.replace(~r/(\s|-)+/u, "-")
end
defimpl Phoenix.Param, for: Artikel do
def to_param(%{id: id, title: title}) do
"#{Artikel.spit_title(title)}--#{Integer.to_string(id, 36) |> String.downcase()}"
end
end
end