2022-07-25 20:08:40 -04:00
|
|
|
defmodule Memex.Notes.Note do
|
2022-11-17 22:38:52 -05:00
|
|
|
@moduledoc """
|
|
|
|
Schema for a user-written note
|
|
|
|
"""
|
2022-07-25 20:08:40 -04:00
|
|
|
use Ecto.Schema
|
|
|
|
import Ecto.Changeset
|
2022-11-17 22:38:52 -05:00
|
|
|
alias Ecto.UUID
|
|
|
|
alias Memex.{Accounts.User, Notes.Note}
|
2022-07-25 20:08:40 -04:00
|
|
|
|
|
|
|
@primary_key {:id, :binary_id, autogenerate: true}
|
|
|
|
@foreign_key_type :binary_id
|
|
|
|
schema "notes" do
|
|
|
|
field :content, :string
|
2022-11-17 22:38:52 -05:00
|
|
|
field :tags, {:array, :string}
|
|
|
|
field :tags_string, :string, virtual: true
|
2022-07-25 20:08:40 -04:00
|
|
|
field :title, :string
|
|
|
|
field :visibility, Ecto.Enum, values: [:public, :private, :unlisted]
|
|
|
|
|
2022-11-17 22:38:52 -05:00
|
|
|
belongs_to :user, User
|
|
|
|
|
2022-07-25 20:08:40 -04:00
|
|
|
timestamps()
|
|
|
|
end
|
|
|
|
|
2022-11-17 22:38:52 -05:00
|
|
|
@type t :: %Note{}
|
|
|
|
@type id :: UUID.t()
|
|
|
|
|
2022-07-25 20:08:40 -04:00
|
|
|
@doc false
|
2022-11-17 22:38:52 -05:00
|
|
|
def create_changeset(attrs, %User{id: user_id}) do
|
|
|
|
%Note{}
|
|
|
|
|> cast(attrs, [:title, :content, :tags, :visibility])
|
|
|
|
|> change(user_id: user_id)
|
|
|
|
|> cast_tags_string(attrs)
|
|
|
|
|> validate_required([:title, :content, :user_id, :visibility])
|
|
|
|
end
|
|
|
|
|
|
|
|
def update_changeset(%{user_id: user_id} = note, attrs, %User{id: user_id}) do
|
2022-07-25 20:08:40 -04:00
|
|
|
note
|
2022-11-17 22:38:52 -05:00
|
|
|
|> cast(attrs, [:title, :content, :tags, :visibility])
|
|
|
|
|> cast_tags_string(attrs)
|
|
|
|
|> validate_required([:title, :content, :visibility])
|
2022-07-25 20:08:40 -04:00
|
|
|
end
|
2022-11-17 22:38:52 -05:00
|
|
|
|
|
|
|
defp cast_tags_string(changeset, %{"tags_string" => tags_string}) when is_binary(tags_string) do
|
|
|
|
tags =
|
|
|
|
tags_string
|
|
|
|
|> String.split(",", trim: true)
|
|
|
|
|> Enum.map(fn str -> str |> String.trim() end)
|
|
|
|
|> Enum.sort()
|
|
|
|
|
|
|
|
changeset |> change(tags: tags)
|
|
|
|
end
|
|
|
|
|
|
|
|
defp cast_tags_string(changeset, _attrs), do: changeset
|
2022-07-25 20:08:40 -04:00
|
|
|
end
|