My space on the web https://inhji.de
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

64 lines
1.3 KiB

defmodule Mirage.Links.Link do
use Ecto.Schema
import Ecto.Changeset
schema "links" do
field :title, :string
field :url, :string
field :domain, :string
many_to_many :notes, Mirage.Notes.Note, join_through: "notes_links"
many_to_many :topics, Mirage.Topics.Topic, join_through: "links_topics"
field :topic_string, :string,
virtual: true,
default: ""
end
@doc false
def changeset(link, attrs) do
link
|> cast(attrs, [:title, :url, :domain])
|> validate_required(:url)
|> unique_constraint(:url)
|> maybe_extract_domain()
|> normalize_url()
|> Mirage.Tags.maybe_load_tag_string()
end
defp normalize_url(changeset) do
case get_change(changeset, :url) do
nil ->
changeset
url ->
changeset
|> put_change(:url, do_normalize_url(url))
end
end
defp do_normalize_url(url) do
url
|> URI.parse()
|> URI.to_string()
|> String.trim_trailing("/")
end
defp maybe_extract_domain(changeset) do
case get_change(changeset, :url) do
nil ->
changeset
url ->
changeset
|> put_change(:url, String.trim(url))
|> put_change(:domain, do_extract_domain(url))
end
end
defp do_extract_domain(url) do
url
|> URI.parse()
|> Map.get(:host)
end
end