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

66 lines
1.5 KiB
Elixir
Raw Normal View History

2024-08-04 13:21:15 +02:00
defmodule Todo.Server do
use GenServer
2024-08-07 00:09:00 +02:00
def start(name) do
GenServer.start(__MODULE__, name)
2024-08-04 13:21:15 +02:00
end
2024-08-07 00:09:00 +02:00
def add(pid, entry) do
GenServer.cast(pid, {:add, entry})
2024-08-04 13:21:15 +02:00
end
2024-08-07 00:09:00 +02:00
def entries(pid, date) do
GenServer.call(pid, {:entries, date})
2024-08-04 13:21:15 +02:00
end
2024-08-07 00:09:00 +02:00
def update(pid, id, update_fun) do
GenServer.cast(pid, {:update, id, update_fun})
end
2024-08-04 13:21:15 +02:00
2024-08-07 00:09:00 +02:00
def delete(pid, id) do
GenServer.cast(pid, {:delete, id})
2024-08-04 13:21:15 +02:00
end
@impl GenServer
2024-08-07 00:09:00 +02:00
def init(name) do
{:ok, {name, nil}, {:continue, :init}}
2024-08-04 13:21:15 +02:00
end
@impl GenServer
2024-08-07 00:09:00 +02:00
def handle_continue(:init, {name, nil}) do
todo_list = Todo.Database.get(name) || Todo.List.new()
{:noreply, {name, todo_list}}
2024-08-04 13:21:15 +02:00
end
2024-08-07 00:09:00 +02:00
@impl GenServer
def handle_call({:entries, date}, _from, {name, todo_list}) do
entries = Todo.List.entries(todo_list, date)
2024-08-04 13:21:15 +02:00
2024-08-07 00:09:00 +02:00
{:reply, entries, {name, todo_list}}
2024-08-04 13:21:15 +02:00
end
2024-08-07 00:09:00 +02:00
@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)
2024-08-04 13:21:15 +02:00
2024-08-07 00:09:00 +02:00
{:noreply, {name, new_todo_list}}
2024-08-04 13:21:15 +02:00
end
2024-08-07 00:09:00 +02:00
@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)
2024-08-04 13:21:15 +02:00
2024-08-07 00:09:00 +02:00
{:noreply, {name, new_todo_list}}
2024-08-04 13:21:15 +02:00
end
2024-08-07 00:09:00 +02:00
@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}}
2024-08-04 13:21:15 +02:00
end
end