feat: use GenServer

main
Moritz Böhme 2024-08-03 22:21:55 +02:00
parent 56ba54e2d7
commit 323d35cad2
Signed by: moritz
GPG Key ID: 970C6E89EB0547A9
1 changed files with 36 additions and 58 deletions

View File

@ -1,90 +1,68 @@
defmodule ServerProcess do
def start(callback_module) do
spawn(fn ->
initial_state = callback_module.init()
loop(callback_module, initial_state)
end)
end
defp loop(callback_module, current_state) do
receive do
{:call, request, caller} ->
{response, new_state} = callback_module.handle_call(request, current_state)
send(caller, {:response, response})
loop(callback_module, new_state)
{:cast, request} ->
new_state = callback_module.handle_cast(request, current_state)
loop(callback_module, new_state)
end
end
def call(pid, message) do
send(pid, {:call, message, self()})
receive do
{:response, response} ->
response
end
end
def cast(pid, message) do
send(pid, {:cast, message})
nil
end
end
defmodule TodoServer do
def init(entries) do
TodoList.new(entries)
use GenServer
@impl GenServer
def init(%_{} = todo_list) do
{:ok, todo_list}
end
def handle_call({:entries, date}, todo_list) do
@impl GenServer
def init(entries) do
{:ok, TodoList.new(entries)}
end
@impl GenServer
def handle_call({:entries, date}, _from, todo_list) do
entries = TodoList.entries(todo_list, date)
{entries, todo_list}
end
def handle_call(invalid_message, todo_list) do
IO.puts("Invalid message: #{IO.inspect(invalid_message)}")
todo_list
{:reply, entries, todo_list}
end
@impl GenServer
def handle_cast({:add, entry}, todo_list) do
TodoList.add(todo_list, entry)
new_todo_list = TodoList.add(todo_list, entry)
{:no_reply, new_todo_list}
end
@impl GenServer
def handle_cast({:update, id, update_fun}, todo_list) do
TodoList.update(todo_list, id, update_fun)
new_todo_list = TodoList.update(todo_list, id, update_fun)
{:no_reply, new_todo_list}
end
@impl GenServer
def handle_cast({:delete, id}, todo_list) do
TodoList.delete(todo_list, id)
new_todo_list = TodoList.delete(todo_list, id)
{:no_reply, new_todo_list}
end
def handle_cast(invalid_message, todo_list) do
IO.puts("Invalid message: #{IO.inspect(invalid_message)}")
def start(entries \\ [])
todo_list
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
ServerProcess.cast(pid, {:add, entry})
GenServer.cast(pid, {:add, entry})
end
def entries(pid, date) do
ServerProcess.call(pid, {:entries, date})
GenServer.call(pid, {:entries, date})
end
def update(pid, id, update_fun) do
ServerProcess.cast(pid, {:update, id, update_fun})
GenServer.cast(pid, {:update, id, update_fun})
end
def delete(pid, id) do
ServerProcess.cast(pid, {:delete, id})
GenServer.cast(pid, {:delete, id})
end
end