Refactoring of Admin context

This commit is contained in:
miffy 2019-09-08 02:06:28 +02:00
parent f78032495c
commit 5d2d4a91c9
2 changed files with 28 additions and 25 deletions

View File

@ -1,27 +1,42 @@
defmodule Mobilizon.Admin.ActionLog do defmodule Mobilizon.Admin.ActionLog do
@moduledoc """ @moduledoc """
ActionLog entity schema Represents an action log entity.
""" """
use Ecto.Schema use Ecto.Schema
import Ecto.Changeset import Ecto.Changeset
alias Mobilizon.Actors.Actor alias Mobilizon.Actors.Actor
@required_attrs [:action, :target_type, :target_id, :changes, :actor_id] @type t :: %__MODULE__{
action: String.t(),
target_type: String.t(),
target_id: integer,
changes: map,
actor: Actor.t()
}
@required_attrs [:action, :target_type, :target_id, :actor_id]
@optional_attrs [:changes]
@attrs @required_attrs ++ @optional_attrs
schema "admin_action_logs" do schema "admin_action_logs" do
field(:action, :string) field(:action, :string)
field(:target_type, :string) field(:target_type, :string)
field(:target_id, :integer) field(:target_id, :integer)
field(:changes, :map) field(:changes, :map)
belongs_to(:actor, Actor) belongs_to(:actor, Actor)
timestamps() timestamps()
end end
@doc false @doc false
@spec changeset(t | Ecto.Changeset.t(), map) :: Ecto.Changeset.t()
def changeset(action_log, attrs) do def changeset(action_log, attrs) do
action_log action_log
|> cast(attrs, @required_attrs) |> cast(attrs, @attrs)
|> validate_required(@required_attrs -- [:changes]) |> validate_required(@required_attrs)
end end
end end

View File

@ -9,39 +9,27 @@ defmodule Mobilizon.Admin do
alias Mobilizon.Storage.{Page, Repo} alias Mobilizon.Storage.{Page, Repo}
@doc """ @doc """
Returns the list of action_logs. Returns the list of action logs.
## Examples
iex> list_action_logs()
[%ActionLog{}, ...]
""" """
@spec list_action_logs(integer(), integer()) :: list(ActionLog.t()) @spec list_action_logs(integer | nil, integer | nil) :: [ActionLog.t()]
def list_action_logs(page \\ nil, limit \\ nil) do def list_action_logs(page \\ nil, limit \\ nil) do
from( list_action_logs_query()
r in ActionLog,
preload: [:actor]
)
|> Page.paginate(page, limit) |> Page.paginate(page, limit)
|> Repo.all() |> Repo.all()
end end
@doc """ @doc """
Creates a action_log. Creates a action_log.
## Examples
iex> create_action_log(%{field: value})
{:ok, %ActionLog{}}
iex> create_action_log(%{field: bad_value})
{:error, %Ecto.Changeset{}}
""" """
@spec create_action_log(map) :: {:ok, ActionLog.t()} | {:error, Ecto.Changeset.t()}
def create_action_log(attrs \\ %{}) do def create_action_log(attrs \\ %{}) do
%ActionLog{} %ActionLog{}
|> ActionLog.changeset(attrs) |> ActionLog.changeset(attrs)
|> Repo.insert() |> Repo.insert()
end end
@spec list_action_logs_query :: Ecto.Query.t()
defp list_action_logs_query do
from(r in ActionLog, preload: [:actor])
end
end end