defmodule EslHnWeb.API.Socket do @moduledoc """ WebSocket API for serving top stories news """ @behaviour Phoenix.Socket.Transport alias EslHnWeb.API.JSON, as: View @impl true def child_spec(_opts), do: :ignore @impl true def connect(_connect_info) do {:ok, []} end @impl true def init(state) do # No support for `handle_continue/2` so we need to hack it around send(self(), :do_init) EslHn.subscribe_new() {:ok, state} end @impl true def handle_in({_message, _opts}, state) do # Ignore all incoming messages {:ok, state} end @impl true def handle_info(:do_init, state) do stories = EslHn.all(1, 50) data = View.index(%{items: stories}) {:push, {:text, JSON.encode_to_iodata!(data)}, state} end def handle_info({:new_stories, stories}, state) do data = View.index(%{items: stories}) {:push, {:text, JSON.encode_to_iodata!(data)}, state} end @impl true def terminate(_reason, _state), do: :ok end