this repo has no description
at main 1.0 kB view raw
1defmodule EslHnWeb.API.Socket do 2 @moduledoc """ 3 WebSocket API for serving top stories news 4 """ 5 6 @behaviour Phoenix.Socket.Transport 7 8 alias EslHnWeb.API.JSON, as: View 9 10 @impl true 11 def child_spec(_opts), do: :ignore 12 13 @impl true 14 def connect(_connect_info) do 15 {:ok, []} 16 end 17 18 @impl true 19 def init(state) do 20 # No support for `handle_continue/2` so we need to hack it around 21 send(self(), :do_init) 22 EslHn.subscribe_new() 23 24 {:ok, state} 25 end 26 27 @impl true 28 def handle_in({_message, _opts}, state) do 29 # Ignore all incoming messages 30 {:ok, state} 31 end 32 33 @impl true 34 def handle_info(:do_init, state) do 35 stories = EslHn.all(1, 50) 36 data = View.index(%{items: stories}) 37 38 {:push, {:text, JSON.encode_to_iodata!(data)}, state} 39 end 40 41 def handle_info({:new_stories, stories}, state) do 42 data = View.index(%{items: stories}) 43 44 {:push, {:text, JSON.encode_to_iodata!(data)}, state} 45 end 46 47 @impl true 48 def terminate(_reason, _state), do: :ok 49end