34 lines
689 B
Elixir
34 lines
689 B
Elixir
defmodule Todo.Cache do
|
|
use GenServer
|
|
|
|
@impl GenServer
|
|
def init(_init_args) do
|
|
IO.puts("Starting #{__MODULE__}")
|
|
|
|
{:ok, %{}}
|
|
end
|
|
|
|
@impl GenServer
|
|
def handle_call({:server_process, name}, _from, state) do
|
|
case Map.fetch(state, name) do
|
|
{:ok, process} ->
|
|
{:reply, process, state}
|
|
|
|
:error ->
|
|
{:ok, new_process} = Todo.Server.start_link(name)
|
|
|
|
new_state = Map.put(state, name, new_process)
|
|
|
|
{:reply, new_process, new_state}
|
|
end
|
|
end
|
|
|
|
def start_link(_) do
|
|
GenServer.start_link(__MODULE__, nil, name: __MODULE__)
|
|
end
|
|
|
|
def server_process(name) do
|
|
GenServer.call(__MODULE__, {:server_process, name})
|
|
end
|
|
end
|