feat: Include selftext and order comments

This commit is contained in:
Daniel Kempkens 2023-08-15 20:52:53 +02:00
parent 889d7d6785
commit 579dd239e7
Signed by: daniel
SSH key fingerprint: SHA256:Ks/MyhQYcPRQiwMKLAKquWCdCPe3JXlb1WttgnAoSeM
6 changed files with 37 additions and 4 deletions

View file

@ -3,7 +3,7 @@ defmodule BdfrBrowser.Comment do
import Ecto.Query, only: [from: 2]
alias BdfrBrowser.Post
alias BdfrBrowser.{Post, Repo}
@primary_key {:id, :string, autogenerate: false}
@foreign_key_type :string
@ -19,6 +19,10 @@ defmodule BdfrBrowser.Comment do
has_many :children, __MODULE__, foreign_key: :parent_id
end
def fetch_children!(comment) do
Repo.preload(comment, children: from(c in __MODULE__, order_by: [asc: c.posted_at])).children
end
def by_author(author) do
from(c in __MODULE__,
join: p in assoc(c, :post),

View file

@ -47,7 +47,7 @@ defmodule BdfrBrowser.HTTP.Plug do
end
get "/r/:subreddit/:date/:id" do
post_record = Post |> Repo.get(id) |> Repo.preload(comments: :children)
post_record = id |> Post.get_full() |> Repo.one()
tpl_args = [
subreddit: subreddit,

View file

@ -47,6 +47,20 @@ defmodule BdfrBrowser.Post do
)
end
def get_full(id) do
from(p in __MODULE__,
where: p.id == ^id,
preload: [
comments:
^from(c in Comment,
where: is_nil(c.parent_id),
order_by: [asc: c.posted_at],
preload: [children: ^from(c1 in Comment, order_by: [asc: c1.posted_at])]
)
]
)
end
def by_author(author) do
from(p in __MODULE__,
join: c in assoc(p, :comments),

View file

@ -1,4 +1,8 @@
defmodule BdfrBrowser.RenderUtils do
def selftext(txt) do
Earmark.as_html!(txt)
end
def comment(cmt) do
Earmark.as_html!(cmt)
end

View file

@ -17,6 +17,6 @@
</div>
</div>
<%= for reply <- BdfrBrowser.Repo.preload(comment, :children).children do %>
<%= for reply <- BdfrBrowser.Comment.fetch_children!(comment) do %>
<%= EEx.eval_file(comment_template, comment: reply, level: level + 1, comment_template: comment_template) %>
<% end %>

View file

@ -8,6 +8,15 @@
<a href="https://reddit.com<%= post.permalink %>">Open reddit</a>
</p>
<%= unless is_nil(post.selftext) do %>
<div class="row">
<blockquote class="blockquote mb-0">
<%= BdfrBrowser.RenderUtils.selftext(post.selftext) %>
</blockquote>
</div>
<br>
<% end %>
<%= unless Enum.empty?(media.images) do %>
<div id="carouselImages" class="carousel slide">
<div class="carousel-inner">
@ -43,6 +52,8 @@
<%= for comment when is_nil(comment.parent_id) <- post.comments do %>
<div class="row" style="margin-bottom: 4px;">
<div class="d-grid gap-2 col-12 mx-auto">
<%= EEx.eval_file(comment_template, comment: comment, level: 0, comment_template: comment_template) %>
</div>
</div>
<% end %>