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

68 lines
1.3 KiB
Elixir
Raw Normal View History

2024-08-04 13:21:15 +02:00
defmodule Todo.Server do
use GenServer
@impl GenServer
def init(%_{} = todo_list) do
{:ok, todo_list}
end
@impl GenServer
def init(entries) do
{:ok, Todo.List.new(entries)}
end
@impl GenServer
def handle_call({:entries, date}, _from, todo_list) do
entries = Todo.List.entries(todo_list, date)
{:reply, entries, todo_list}
end
@impl GenServer
def handle_cast({:add, entry}, todo_list) do
new_todo_list = Todo.List.add(todo_list, entry)
{:noreply, new_todo_list}
end
@impl GenServer
def handle_cast({:update, id, update_fun}, todo_list) do
new_todo_list = Todo.List.update(todo_list, id, update_fun)
{:noreply, new_todo_list}
end
@impl GenServer
def handle_cast({:delete, id}, todo_list) do
new_todo_list = Todo.List.delete(todo_list, id)
{:noreply, new_todo_list}
end
def start(entries \\ [])
def start(%_{} = todo_list) do
GenServer.start(__MODULE__, todo_list)
end
def start(entries) do
GenServer.start(__MODULE__, entries)
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
end