feat(server): hosts list/delete/rotate helpers + pubsub on metric insert
This commit is contained in:
parent
f3e7fab4d2
commit
3123743c1c
4 changed files with 77 additions and 2 deletions
|
|
@ -63,4 +63,27 @@ defmodule Server.Hosts do
|
|||
defp generate_token do
|
||||
:crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
|
||||
end
|
||||
|
||||
@spec list_all() :: [Host.t()]
|
||||
def list_all do
|
||||
import Ecto.Query
|
||||
Repo.all(from h in Host, order_by: [asc: h.name])
|
||||
end
|
||||
|
||||
@spec delete_host(Host.t()) :: {:ok, Host.t()} | {:error, Ecto.Changeset.t()}
|
||||
def delete_host(%Host{} = host), do: Repo.delete(host)
|
||||
|
||||
@spec rotate_token(Host.t()) :: {:ok, {Host.t(), String.t()}} | {:error, Ecto.Changeset.t()}
|
||||
def rotate_token(%Host{} = host) do
|
||||
token = generate_token()
|
||||
hash = Bcrypt.hash_pwd_salt(token)
|
||||
|
||||
host
|
||||
|> Ecto.Changeset.change(token_hash: hash)
|
||||
|> Repo.update()
|
||||
|> case do
|
||||
{:ok, updated} -> {:ok, {updated, token}}
|
||||
{:error, cs} -> {:error, cs}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
|||
|
|
@ -18,11 +18,25 @@ defmodule Server.Metrics do
|
|||
})
|
||||
|
||||
with %Ecto.Changeset{valid?: true} = cs <- changeset,
|
||||
true <- host_exists?(host_id) || {:host_missing, cs} do
|
||||
Repo.insert(cs)
|
||||
true <- host_exists?(host_id) || {:host_missing, cs},
|
||||
{:ok, metric} <- Repo.insert(cs) do
|
||||
Phoenix.PubSub.broadcast(
|
||||
Server.PubSub,
|
||||
"metrics",
|
||||
{:metric_inserted, host_id, interval_type}
|
||||
)
|
||||
|
||||
Phoenix.PubSub.broadcast(
|
||||
Server.PubSub,
|
||||
"metrics:#{host_id}",
|
||||
{:metric_inserted, host_id, interval_type}
|
||||
)
|
||||
|
||||
{:ok, metric}
|
||||
else
|
||||
%Ecto.Changeset{} = cs -> {:error, cs}
|
||||
{:host_missing, cs} -> {:error, Ecto.Changeset.add_error(cs, :host, "does not exist")}
|
||||
{:error, %Ecto.Changeset{} = cs} -> {:error, cs}
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue