2019-09-08 01:49:56 +02:00
|
|
|
defmodule Mobilizon.Storage.Ecto do
|
|
|
|
@moduledoc """
|
|
|
|
Mobilizon Ecto utils
|
|
|
|
"""
|
|
|
|
|
|
|
|
import Ecto.Query, warn: false
|
2020-08-14 11:32:23 +02:00
|
|
|
import Ecto.Changeset, only: [fetch_change: 2, put_change: 3, get_field: 2]
|
|
|
|
alias Ecto.{Changeset, Query}
|
2020-02-18 08:57:00 +01:00
|
|
|
alias Mobilizon.Web.Endpoint
|
|
|
|
alias Mobilizon.Web.Router.Helpers, as: Routes
|
2019-09-08 01:49:56 +02:00
|
|
|
|
|
|
|
@doc """
|
|
|
|
Adds sort to the query.
|
|
|
|
"""
|
2020-08-14 11:32:23 +02:00
|
|
|
@spec sort(Query.t(), atom, atom) :: Query.t()
|
2019-09-08 01:49:56 +02:00
|
|
|
def sort(query, sort, direction) do
|
|
|
|
from(query, order_by: [{^direction, ^sort}])
|
|
|
|
end
|
2020-02-18 08:57:00 +01:00
|
|
|
|
|
|
|
@doc """
|
|
|
|
Ensure changeset contains an URL
|
|
|
|
|
|
|
|
If there's a blank URL that's because we're doing the first insert.
|
|
|
|
Most of the time just go with the given URL.
|
|
|
|
"""
|
2020-08-14 11:32:23 +02:00
|
|
|
@spec ensure_url(Changeset.t(), atom()) :: Changeset.t()
|
|
|
|
def ensure_url(%Changeset{data: %{url: nil}} = changeset, route) do
|
2020-02-18 08:57:00 +01:00
|
|
|
case fetch_change(changeset, :url) do
|
|
|
|
{:ok, _url} ->
|
|
|
|
changeset
|
|
|
|
|
|
|
|
:error ->
|
|
|
|
generate_url(changeset, route)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-08-14 11:32:23 +02:00
|
|
|
def ensure_url(%Changeset{} = changeset, _route), do: changeset
|
2020-02-18 08:57:00 +01:00
|
|
|
|
2020-08-14 11:32:23 +02:00
|
|
|
@spec generate_url(Changeset.t(), atom()) :: Changeset.t()
|
|
|
|
defp generate_url(%Changeset{} = changeset, route) do
|
2020-02-18 08:57:00 +01:00
|
|
|
uuid = Ecto.UUID.generate()
|
|
|
|
|
|
|
|
changeset
|
|
|
|
|> put_change(:id, uuid)
|
|
|
|
|> put_change(
|
|
|
|
:url,
|
2020-08-12 16:05:34 +02:00
|
|
|
apply(Routes, String.to_existing_atom("page_url"), [Endpoint, route, uuid])
|
2020-02-18 08:57:00 +01:00
|
|
|
)
|
|
|
|
end
|
2020-08-14 11:32:23 +02:00
|
|
|
|
|
|
|
@spec maybe_add_published_at(Changeset.t()) :: Changeset.t()
|
|
|
|
def maybe_add_published_at(%Changeset{} = changeset) do
|
|
|
|
if is_nil(get_field(changeset, :published_at)) do
|
|
|
|
put_change(changeset, :published_at, DateTime.utc_now() |> DateTime.truncate(:second))
|
|
|
|
else
|
|
|
|
changeset
|
|
|
|
end
|
|
|
|
end
|
2019-09-08 01:49:56 +02:00
|
|
|
end
|