44 lines
1.1 KiB
Elixir
44 lines
1.1 KiB
Elixir
defmodule Prymn.Agents.Store do
|
|
@moduledoc false
|
|
use Agent
|
|
|
|
alias Prymn.Agents
|
|
|
|
# Stores and serves locally saved "Prymn Agents" to the application
|
|
# Not to be confused with the "Prymn Server" construct
|
|
|
|
@doc false
|
|
def start_link([]) do
|
|
Agent.start_link(fn -> %{} end, name: __MODULE__)
|
|
end
|
|
|
|
def get(id) do
|
|
Agent.get(__MODULE__, fn agents -> agents[id] end)
|
|
end
|
|
|
|
def get_or_default(id, new_agent \\ nil) do
|
|
case Agent.get(__MODULE__, fn agents -> agents[id] end) do
|
|
nil ->
|
|
agent = new_agent || Agents.Agent.new(id)
|
|
Agent.update(__MODULE__, &Map.put(&1, id, agent))
|
|
agent
|
|
|
|
agent ->
|
|
agent
|
|
end
|
|
end
|
|
|
|
def update_health(id, health) do
|
|
case get(id) do
|
|
nil ->
|
|
agent = %Agents.Agent{Agents.Agent.new(id) | status: :connected, health: health}
|
|
Agent.update(__MODULE__, &Map.put(&1, id, agent))
|
|
agent
|
|
|
|
agent ->
|
|
agent = %Agents.Agent{agent | status: :connected, health: health}
|
|
Agent.update(__MODULE__, &Map.put(&1, id, agent))
|
|
agent
|
|
end
|
|
end
|
|
end
|