Move mod note query string query to context

This commit is contained in:
Liam 2024-07-15 20:57:39 -04:00
parent dd5a118d8c
commit 93a6d8d117
2 changed files with 52 additions and 24 deletions

View file

@ -7,18 +7,56 @@ defmodule Philomena.ModNotes do
alias Philomena.Repo
alias Philomena.ModNotes.ModNote
alias Philomena.Polymorphic
@doc """
Returns the list of mod_notes.
Returns a `m:Scrivener.Page` of 2-tuples of messages and rendered output
for the query string current pagination.
All mod notes containing the substring `query_string` are matched and returned
case-insensitively.
See `list_mod_notes/3` for more information.
## Examples
iex> list_mod_notes()
[%ModNote{}, ...]
iex> list_mod_notes_by_query_string("quack", & &1.body, page_size: 15)
%Scrivener.Page{}
"""
def list_mod_notes do
Repo.all(ModNote)
def list_mod_notes_by_query_string(query_string, collection_renderer, pagination) do
ModNote
|> where([m], ilike(m.body, ^"%#{query_string}%"))
|> list_mod_notes(collection_renderer, pagination)
end
@doc """
Returns a `m:Scrivener.Page` of 2-tuples of messages and rendered output
for the current pagination.
When coerced to a list and rendered as Markdown, the result may look like:
[
{%ModNote{body: "hello *world*"}, "hello <strong>world</strong>"}
]
## Examples
iex> list_mod_notes(& &1.body, page_size: 15)
%Scrivener.Page{}
"""
def list_mod_notes(queryable \\ ModNote, collection_renderer, pagination) do
mod_notes =
queryable
|> preload(:moderator)
|> order_by(desc: :id)
|> Repo.paginate(pagination)
bodies = collection_renderer.(mod_notes)
preloaded = Polymorphic.load_polymorphic(mod_notes, notable: [notable_id: :notable_type])
put_in(mod_notes.entries, Enum.zip(bodies, preloaded))
end
@doc """

View file

@ -5,33 +5,23 @@ defmodule PhilomenaWeb.Admin.ModNoteController do
alias Philomena.ModNotes.ModNote
alias Philomena.Polymorphic
alias Philomena.ModNotes
alias Philomena.Repo
import Ecto.Query
plug :verify_authorized
plug :load_resource, model: ModNote, only: [:edit, :update, :delete]
plug :preload_association when action in [:edit, :update, :delete]
def index(conn, %{"q" => q}) do
ModNote
|> where([m], ilike(m.body, ^"%#{q}%"))
|> load_mod_notes(conn)
end
def index(conn, params) do
pagination = conn.assigns.scrivener
renderer = &MarkdownRenderer.render_collection(&1, conn)
def index(conn, _params) do
load_mod_notes(ModNote, conn)
end
defp load_mod_notes(queryable, conn) do
mod_notes =
queryable
|> preload(:moderator)
|> order_by(desc: :id)
|> Repo.paginate(conn.assigns.scrivener)
case params do
%{"q" => q} ->
ModNotes.list_mod_notes_by_query_string(q, renderer, pagination)
bodies = MarkdownRenderer.render_collection(mod_notes, conn)
preloaded = Polymorphic.load_polymorphic(mod_notes, notable: [notable_id: :notable_type])
mod_notes = %{mod_notes | entries: Enum.zip(bodies, preloaded)}
_ ->
ModNotes.list_mod_notes(renderer, pagination)
end
render(conn, "index.html", title: "Admin - Mod Notes", mod_notes: mod_notes)
end