Skip to content

Commit

Permalink
stateful server 2
Browse files Browse the repository at this point in the history
  • Loading branch information
hexisdylan committed Jul 26, 2022
1 parent 0509fe9 commit d010b38
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/pledge_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule Servy.PledgeController do

def create(conv, %{"name" => name, "amount" => amount}) do
# sends pledge to the external service and caches it
PledgeServer.create_pledge(name, String.to_integer(amount))
Servy.PledgeServer.create_pledge(name, String.to_integer(amount))

%{conv | status: 201, resp_body: "#{name} pledged #{amount}!"}
end
Expand Down
30 changes: 28 additions & 2 deletions lib/pledge_server.ex
Original file line number Diff line number Diff line change
@@ -1,8 +1,34 @@
defmodule Servy.PledgeServer do
def create_pledge(name, amount) do
{:ok, id} = send_pledge_to_service(name, amount)
def listen_loop(state) do
IO.puts("\nWaiting for a message...")

receive do
{:create_pledge, name, amount} ->
{:ok, id} = send_pledge_to_service(name, amount)
new_state = [{name, amount} | state]
IO.puts("#{name} pledged #{amount}!")
IO.puts("New state is #{inspect(new_state)}")
listen_loop(new_state)

{sender, :recent_pledges} ->
send(sender, {:response, state})
IO.puts("Sent pledges to #{inspect(sender)}")
listen_loop(state)
end
end

# def create_pledge(name, amount) do
# {:ok, id} = send_pledge_to_service(name, amount)

# # Cache the pledge:
# [{"larry, 10"}]
# end

# def recent_pledge do
# # Returns the most recent pledges (cache):
# [{"larry, 10"}]
# end

defp send_pledge_to_service(_name, _amount) do
# CODE GOES HERE TO SEND PLEDGE TO EXTERNAL SERVICE
{:ok, "pledge-#{:rand.uniform(1000)}"}
Expand Down

0 comments on commit d010b38

Please sign in to comment.