Browse Source

feat: add views and viewed at fields to notes

main
Inhji Y. 8 months ago
parent
commit
7b6166b681
  1. 8
      lib/mirage/notes.ex
  2. 4
      lib/mirage/notes/note.ex
  3. 9
      lib/mirage_web/live/note_live/show.ex
  4. 10
      priv/repo/migrations/20210221112501_add_views_and_last_viewed_to_notes.exs

8
lib/mirage/notes.ex

@ -154,6 +154,13 @@ defmodule Mirage.Notes do
def preload_note(note), do: Repo.preload(note, @note_preloads)
def view_note!(note),
do:
update_note!(note, %{
views: note.views + 1,
viewed_at: DateTime.utc_now()
})
@doc """
Creates a note.
@ -194,7 +201,6 @@ defmodule Mirage.Notes do
note
|> Note.changeset(attrs)
|> Repo.update!()
|> preload_note()
end
@doc """

4
lib/mirage/notes/note.ex

@ -9,6 +9,8 @@ defmodule Mirage.Notes.Note do
field :title, :string
field :content, :string
field :content_html, :string
field :views, :integer
field :viewed_at, :naive_datetime
many_to_many :links, Link, join_through: "notes_links"
many_to_many :topics, Topic, join_through: "notes_topics"
@ -27,7 +29,7 @@ defmodule Mirage.Notes.Note do
@doc false
def changeset(note, attrs) do
note
|> cast(attrs, [:content, :title])
|> cast(attrs, [:content, :title, :views, :viewed_at])
|> validate_required([:content, :title])
|> Mirage.Markdown.maybe_render_markdown(:content, :content_html)
|> maybe_load_tag_string()

9
lib/mirage_web/live/note_live/show.ex

@ -5,6 +5,9 @@ defmodule MirageWeb.NoteLive.Show do
alias Mirage.Links
alias Mirage.Links.Link
defp page_title(:show), do: "Show Note"
defp page_title(:edit), do: "Edit Note"
@impl true
def mount(_params, %{"user_id" => user_id}, socket) do
{:ok, socket |> assign(:current_user, Mirage.Accounts.get_user!(user_id))}
@ -18,6 +21,7 @@ defmodule MirageWeb.NoteLive.Show do
|> assign(
:note,
Notes.get_note!(id)
|> Notes.view_note!()
|> Notes.preload_note()
)
|> assign(:link_changeset, Link.changeset(%Link{}, %{note_id: id}))}
@ -31,9 +35,6 @@ defmodule MirageWeb.NoteLive.Show do
{:noreply, push_redirect(socket, to: Routes.note_index_path(socket, :index))}
end
defp page_title(:show), do: "Show Note"
defp page_title(:edit), do: "Edit Note"
def handle_event("delete_link", %{"link-id" => link_id}, socket) do
link = Links.get_link!(link_id)
{:ok, _} = Links.delete_link(link)
@ -41,6 +42,7 @@ defmodule MirageWeb.NoteLive.Show do
note =
socket.assigns.note.id
|> Notes.get_note!()
|> Notes.view_note!()
|> Notes.preload_note()
{:noreply, socket |> assign(%{note: note})}
@ -55,6 +57,7 @@ defmodule MirageWeb.NoteLive.Show do
note =
note_id
|> Notes.get_note!()
|> Notes.view_note!()
|> Notes.preload_note()
{:noreply,

10
priv/repo/migrations/20210221112501_add_views_and_last_viewed_to_notes.exs

@ -0,0 +1,10 @@
defmodule Mirage.Repo.Migrations.AddViewsAndLastViewedToNotes do
use Ecto.Migration
def change do
alter table(:notes) do
add :views, :integer, default: 0
add :viewed_at, :naive_datetime
end
end
end
Loading…
Cancel
Save