Elixir Phoenix Restful to websocket API

1.1k views Asked by At

RESTful to websocket API question: I want to enable a RESTful api that interfaces with websockets.

I have some hardware that maintains a WS connection to my Phx.server, and I would like to allow other clients to hit the phx.server via a RESTful api and interact with WS connected hardware.

The part I have not figured out is the response for RESTful call, i.e. the http response. Suppose I want a client to be able to request the current temperature from a sensor on the hardware connected via WS.

I can broadcast to the WS via the controller using Phoenix.Endpoint.broadcast(topic, event, msg), but I want to “wait” for a response so that I can send the temp back in the HTTP response from the client. Any suggestions appreciated.

1

There are 1 answers

2
webdeb On

I am not sure, but I would try something similar to this:

send the conn struct to your socket device which will include it inside the response.

And implement a handle_in callback inside your Channel which will handle the response from your Socket, with the conn struct, so that you can reuse it, to send the response to your HTTP client:

  # Send the connection to your socket
  Phoenix.Endpoint.broadcast(topic, event, %{"conn" => conn})

  #
  def handle_in("temperature_response", %{"temperature" => t, "conn" => conn}, socket) do
    render(conn, "temperature.json", %{"temperature" => t})
    {:noreply, socket}
  end