Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

connect the dots #101

Open
setop opened this issue Jan 28, 2024 · 0 comments
Open

connect the dots #101

setop opened this issue Jan 28, 2024 · 0 comments

Comments

@setop
Copy link

setop commented Jan 28, 2024

I wanted to implement an example where I POST messages to an endpoint and all http client connected on sse endpoint receive them.

I managed to do it with "plug" and "phoenix_pubsub".
But I failed to put all pieces together using SSE.Stream and EventBus.

Here is my code:

Mix.install([
  {:bandit, "~> 1.1.3"},
  {:sse, "~> 0.4"},
  {:event_bus, ">= 1.6.0"},
  {:uuid, "~> 1.1"}
])

defmodule Router do
  
  use Plug.Router
  import SSE
  import EventBus
  alias SSE.Chunk
  alias EventBus.Model.Event

  @topic :inbox

  plug(Plug.Logger)
  plug(:match)
  plug(:dispatch)

  post "/inbox" do
    chunk = %Chunk{data: '{"a":"b"}'}
    event = %Event{id: UUID.uuid4(), data: chunk, topic: @topic}
    EventBus.notify(event)
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(200, '{"result":"ok"}')
  end

  get "/" do
    conn
    |> put_resp_content_type("text/html")
    |> send_file(200, "index.html")
  end

  get "/sse" do
    chunk = %Chunk{data: "Hi there!"}
    EventBus.subscribe({MyEventSubscriber, [".*"]})
    loop_receive(conn)
  end
  
  def loop_receive(conn) do
    receive do
      {:post, chunk} ->
        conn
        |> SSE.stream({@topic,chunk})
        loop_receive(conn)
    end
  end

  match _ do
    send_resp(conn, 404, "not found")
  end
end

webserver = {Bandit, plug: Router, scheme: :http}
{:ok, _} = Supervisor.start_link([EventBus, webserver], strategy: :one_for_one)

# unless running from IEx, sleep idenfinitely so we can serve requests
unless IEx.started?() do
  Process.sleep(:infinity)
end

It fails with [warning] Topic(:inbox doesn't exist!) doesn't have subscribers when I post messages.

May need a little help :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant