send(parent, {:hello, self()}) end #PID<0.48.0> iex> receive do ...> {:hello, pid} -> "Got hello from #{inspect pid}" ...> end "Got hello from #PID<0.48.0>"
Conflicted.TweetChannel ## Transports transport :websocket, Phoenix.Transports.WebSocket transport :longpoll, Phoenix.Transports.LongPoll def connect(_params, socket) do {:ok, socket} end def id(_socket), do: nil end
tweets = Repo.all(Tweet) {:ok, tweets, socket} end def join("tweets:" <> _private_room_id, _params, _socket) do {:error, %{reason: "unauthorized"}} end # … end Return an error if the client tries to join any other channel
all of the clients Pattern match on the action def handle_in("action", %{"type" => "LIKE_TWEET", "id" => id}, socket) do changeset = Tweet |> Repo.get!(id) |> Tweet.changeset(%{"likes" => tweet.likes+1}) case Repo.update(changeset) do {:ok, tweet} -> broadcast!(socket, "state", tweet) {:error, changeset} -> IO.puts "SOMETHING WENT WRONG" IO.inspect changeset end {:noreply, socket} end
:author, :string field :content, :string field :source_url, :string field :image_url, :string field :likes, :integer, default: 0 timestamps end @required_fields ~w(author content source_url image_url) @optional_fields ~w(likes) def changeset(model, params \\ []) do model |> cast(params, @required_fields, @optional_fields) |> validate_number(:likes, greater_than_or_equal_to: 0) end end
\\ []) do model |> cast(params, @required_fields, @optional_fields) |> validate_number(:likes, greater_than_or_equal_to: 0) end Transform into changeset
\\ []) do model |> cast(params, @required_fields, @optional_fields) |> validate_number(:likes, greater_than_or_equal_to: 0) end Transform into changeset Provide some validation
id}, socket) do changeset = Tweet |> Repo.get!(id) |> Tweet.changeset(%{"likes" => tweet.likes+1}) case Repo.update(changeset) do {:ok, tweet} -> broadcast!(socket, "state", tweet) {:error, changeset} -> IO.puts "SOMETHING WENT WRONG" IO.inspect changeset end {:noreply, socket} end Execute the change Handle the response