balls/lib/balls_pds/ecto/schema/agent.ex

45 lines
1.0 KiB
Elixir

defmodule BallsPDS.Ecto.Schema.Agent do
use Ecto.Schema
import Ecto.Changeset
import BallsPDS.Util.ACL, only: [validate_acl: 2]
import Ecto.Query
alias BallsPDS.Repo
schema "agents" do
field(:acl, :string)
field(:public_key, :string)
field(:disabled, :boolean, default: false)
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [
:acl,
:public_key,
:disabled
])
|> validate_required([:acl, :disabled])
|> validate_acl(:acl)
|> validate_inclusion(:disabled, [true, false])
end
def get_by_acl(acl) when is_binary(acl) do
query = from a in __MODULE__,
where: a.acl == ^acl
Repo.one(query)
end
def get_or_create_by_acl(acl) when is_binary(acl) do
with {:existing, nil} <- {:existing, get_by_acl(acl)},
{:insert, {:ok, new}} <- {:insert, Repo.insert(%__MODULE__{acl: acl, disabled: false})} do
{:ok, new}
else
{:existing, existing} -> {:ok, existing}
{:insert, {:error, _} = error} -> error
end
end
end