elixir-todo-list/lib/todo/database_worker.ex

58 lines
1.3 KiB
Elixir
Raw Normal View History

2024-08-07 00:48:49 +02:00
defmodule Todo.DatabaseWorker do
use GenServer
2024-08-07 10:03:31 +02:00
def start_link({_db_folder, worker_id} = state) do
GenServer.start_link(__MODULE__, state, name: via_tuple(worker_id))
2024-08-07 00:48:49 +02:00
end
2024-08-07 10:03:31 +02:00
def store(worker_id, key, data) do
worker_id
|> via_tuple()
|> GenServer.cast({:store, key, data})
2024-08-07 00:48:49 +02:00
end
2024-08-07 10:03:31 +02:00
def get(worker_id, key) do
worker_id
|> via_tuple()
|> GenServer.call({:get, key})
end
defp via_tuple(worker_id) do
Todo.ProcessRegistry.via_tuple({__MODULE__, worker_id})
2024-08-07 00:48:49 +02:00
end
@impl GenServer
2024-08-07 10:03:31 +02:00
def init({db_folder, worker_id} = state) do
IO.puts("Starting #{__MODULE__} #{worker_id} with db folder #{db_folder}.")
2024-08-07 08:21:57 +02:00
2024-08-07 10:03:31 +02:00
{:ok, state}
2024-08-07 00:48:49 +02:00
end
@impl GenServer
2024-08-07 10:03:31 +02:00
def handle_cast({:store, key, data}, {db_folder, _worker_id} = state) do
2024-08-07 00:48:49 +02:00
{db_folder, key}
|> file_name()
|> File.write!(:erlang.term_to_binary(data))
2024-08-07 10:03:31 +02:00
{:noreply, state}
2024-08-07 00:48:49 +02:00
end
@impl GenServer
2024-08-07 10:03:31 +02:00
def handle_call({:get, key}, _, {db_folder, _worker_id} = state) do
2024-08-07 00:48:49 +02:00
data =
case File.read(file_name({db_folder, key})) do
{:ok, contents} ->
:erlang.binary_to_term(contents)
2024-08-07 10:33:19 +02:00
{:error, :enoent} ->
2024-08-07 00:48:49 +02:00
nil
end
2024-08-07 10:03:31 +02:00
{:reply, data, state}
2024-08-07 00:48:49 +02:00
end
def file_name({db_folder, key}) do
Path.join(db_folder, to_string(key))
end
end