From 8355f3094813e85bd8ef28bff22d72d824361858 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Moritz=20B=C3=B6hme?= Date: Sun, 4 Aug 2024 13:56:50 +0200 Subject: [PATCH] feat: add server cache --- lib/todo/cache.ex | 31 +++++++++++++++++++++++++++++++ test/todo/cache_test.exs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 lib/todo/cache.ex create mode 100644 test/todo/cache_test.exs diff --git a/lib/todo/cache.ex b/lib/todo/cache.ex new file mode 100644 index 0000000..724b539 --- /dev/null +++ b/lib/todo/cache.ex @@ -0,0 +1,31 @@ +defmodule Todo.Cache do + use GenServer + + @impl GenServer + def init(_init_args) do + {: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 -> + new_process = Todo.Server.start() + + new_state = Map.put(state, name, new_process) + + {:reply, new_process, new_state} + end + end + + def start() do + GenServer.start(__MODULE__, nil) + end + + def server_process(pid, name) do + GenServer.call(pid, {:server_process, name}) + end +end diff --git a/test/todo/cache_test.exs b/test/todo/cache_test.exs new file mode 100644 index 0000000..e5a55ff --- /dev/null +++ b/test/todo/cache_test.exs @@ -0,0 +1,36 @@ +defmodule Todo.TestCache do + use ExUnit.Case + alias Todo.Cache + alias Todo.Server + + test "different names get different servers" do + {:ok, pid} = Cache.start() + + {:ok, alice_server} = Cache.server_process(pid, "Alice") + + {:ok, bob_server} = Cache.server_process(pid, "Bob") + + assert alice_server != bob_server + end + + test "same name gets same server" do + {:ok, pid} = Cache.start() + + {:ok, alice_server} = Cache.server_process(pid, "Alice") + + {:ok, alice_server2} = Cache.server_process(pid, "Alice") + + assert alice_server == alice_server2 + end + + test "simple usage" do + {:ok, pid} = Cache.start() + + {:ok, alice_server} = Cache.server_process(pid, "Alice") + + Server.add(alice_server, %{date: ~D[2024-08-04], title: "Learn Elixir"}) + + assert [%{date: ~D[2024-08-04], title: "Learn Elixir"}] = + Server.entries(alice_server, ~D[2024-08-04]) + end +end