I've built the basic chat application showed in the Phoenix Channels docs. Now I want a way to handle certain messages by replying only to the sender.
Eg, if the user types /who
, send them (and only them) a list of connected users.
How can I do this?
The matching handle_in
function head needs to return a response formatted like this: {:reply, {status :: atom, response :: map}, Socket.t}
.
For example:
def handle_in("new_msg", %{"body" => "/who"}, socket) do
user_list = UserList.get # or whatever
{:reply, {:ok, %{kind: "private", from: "server", body: user_list}}, socket}
end
(If you set handle_in
to return garbage, like an empty string, the resulting error explains the acceptable return value formats, which is where I learned this.)
When you channel.push
, just chain on a .receive
for the reply.
channel.push("new_msg", {body: $chatInput.val()}).receive(
"ok", (reply) => console.log("got reply", reply)
)
(Thanks to Manuel Kallenbach for this answer.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With