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)
|
|
|
|
|
|
|
|
_ ->
|
|
|
|
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
|