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

50 lines
973 B
Elixir
Raw Normal View History

2024-08-07 00:48:49 +02:00
defmodule Todo.DatabaseWorker do
use GenServer
def start(db_folder) do
GenServer.start(__MODULE__, db_folder)
end
def store(pid, key, data) do
GenServer.cast(pid, {:store, key, data})
end
def get(pid, key) do
GenServer.call(pid, {:get, key})
end
@impl GenServer
def init(db_folder) do
2024-08-07 08:21:57 +02:00
IO.puts("Starting #{__MODULE__} with db folder #{db_folder}.")
2024-08-07 00:48:49 +02:00
{:ok, db_folder}
end
@impl GenServer
def handle_cast({:store, key, data}, db_folder) do
{db_folder, key}
|> file_name()
|> File.write!(:erlang.term_to_binary(data))
{:noreply, db_folder}
end
@impl GenServer
def handle_call({:get, key}, _, db_folder) do
data =
case File.read(file_name({db_folder, key})) do
{:ok, contents} ->
:erlang.binary_to_term(contents)
_ ->
nil
end
{:reply, data, db_folder}
end
def file_name({db_folder, key}) do
Path.join(db_folder, to_string(key))
end
end