71 lines
1.7 KiB
Elixir
71 lines
1.7 KiB
Elixir
defmodule Todo.Server do
|
|
use GenServer, restart: :temporary
|
|
|
|
def start_link(name) do
|
|
GenServer.start_link(__MODULE__, name, name: via_tuple(name))
|
|
end
|
|
|
|
def via_tuple(name) do
|
|
Todo.ProcessRegistry.via_tuple({__MODULE__, name})
|
|
end
|
|
|
|
def add(pid, entry) do
|
|
GenServer.cast(pid, {:add, entry})
|
|
end
|
|
|
|
def entries(pid, date) do
|
|
GenServer.call(pid, {:entries, date})
|
|
end
|
|
|
|
def update(pid, id, update_fun) do
|
|
GenServer.cast(pid, {:update, id, update_fun})
|
|
end
|
|
|
|
def delete(pid, id) do
|
|
GenServer.cast(pid, {:delete, id})
|
|
end
|
|
|
|
@impl GenServer
|
|
def init(name) do
|
|
IO.puts("Starting #{__MODULE__} for #{name}.")
|
|
|
|
{:ok, {name, nil}, {:continue, :init}}
|
|
end
|
|
|
|
@impl GenServer
|
|
def handle_continue(:init, {name, nil}) do
|
|
todo_list = Todo.Database.get(name) || Todo.List.new()
|
|
{:noreply, {name, todo_list}}
|
|
end
|
|
|
|
@impl GenServer
|
|
def handle_call({:entries, date}, _from, {name, todo_list}) do
|
|
entries = Todo.List.entries(todo_list, date)
|
|
|
|
{:reply, entries, {name, todo_list}}
|
|
end
|
|
|
|
@impl GenServer
|
|
def handle_cast({:add, entry}, {name, todo_list}) do
|
|
new_todo_list = Todo.List.add(todo_list, entry)
|
|
Todo.Database.store(name, new_todo_list)
|
|
|
|
{:noreply, {name, new_todo_list}}
|
|
end
|
|
|
|
@impl GenServer
|
|
def handle_cast({:update, id, update_fun}, {name, todo_list}) do
|
|
new_todo_list = Todo.List.update(todo_list, id, update_fun)
|
|
Todo.Database.store(name, new_todo_list)
|
|
|
|
{:noreply, {name, new_todo_list}}
|
|
end
|
|
|
|
@impl GenServer
|
|
def handle_cast({:delete, id}, {name, todo_list}) do
|
|
new_todo_list = Todo.List.delete(todo_list, id)
|
|
Todo.Database.store(name, new_todo_list)
|
|
|
|
{:noreply, {name, new_todo_list}}
|
|
end
|
|
end
|