room channelNow that we have a user interface in place to send and receive messages, we should start putting together our backend to actually handle these messages. This is where Phoenix really shines.
If you're familiar with a socket, you'll pick up channels fairly quickly. If you're not familiar with the concept of websockets, it's best to think of the internet as split between two types of connections: 1) request-response, and 2) sockets.
Request-response is how we're handling our JSON web token. Each time you send a request, the connection (conn) is essentially a new struct that goes through your pipeline and then disappears. A real-world analogy would be sending and receiving letters in the mail; once you write the letter and drop it off (request), you have to wait until you get a response.
Using sockets/channels is more like starting an ongoing conversation with someone standing next to you. The line of communication is always open and feedback is immediate.
What's more, a channel can be stateful, meaning when we connect to a channel we don't have to worry about storing data and keeping track of our conversations. When you start a connection, the socket stays alive and is transformed until the connection is broken.
If this sounds complicated or magical, it should make more sense when we start to implement it.
room channelBased on the way our app works, we're going to create a new room for each of our anonymous customers and list them in the Sidebar. When we click on one of the active chats, we want access to the chat history between the company representative and the anonymous customer.
We're going to use the built-in generator to create our room channel. Remember, you can run mix --help to see all the built-in functions you can run with mix.
$ mix phoenix.gen.channel RoomThen (as it says in the console output), we want to add that channel to our user_socket.ex file. As it turns out, this is already a default option, so you can just un-comment the code that already exists.
We're also going to use the assign function to store data about the user in the socket so we can more easily identify the user (the reason for this will become more clearer when we connect to the frontend). You can think of assign as a way to pass values to other parts of the app on the socket struct/object.
defmodule PhoenixChat.UserSocket do use Phoenix.Socket ## Channels channel "room:*", PhoenixChat.RoomChannel ... def connect(params, socket) do socket = socket |> assign(:user_id, params["id"]) |> assign(:username, params["username"]) |> assign(:email, params["email"]) |> assign(:uuid, params["uuid"]) {:ok, socket} end ...Then we need to handle incoming messages, so within room_channel.ex, add the following (with explanation below the code).
defmodule PhoenixChat.RoomChannel do use PhoenixChat.Web, :channel require Logger def join("room:" <> _uid, payload, socket) do if authorized?(payload) do {:ok, socket} else {:error, %{reason: "unauthorized"}} end end def handle_in("message", payload, socket) do Logger.debug "#{inspect payload}" broadcast socket, "message", payload {:noreply, socket} end ...First, we're adding a join function that tells Phoenix what to do when a frontend attempts to join the socket. In this case, we are using pattern matching to determine what to join. So if an incoming join request starts with the pattern room: with anything following (other than room:lobby from the boilerplate code), the join that we defined will get called.
If we get a pattern that matches, we check to see if the user is authorized. The current authorized? function simply returns true, but this is where we can add authorization later on. If the user is authorized, it returns the socket allowing us to connect to it.
Note: in Elixir, question marks (?) are valid characters in function names.
The next function we're adding is handle_in, which is one of the built-in functions that Phoenix looks for when the socket receives an incoming request. In our case, we want to listen for a request that matches the pattern message (which is an arbitrary title; you could name it whatever you want) then broadcast that message to everything on the frontend that is currently listening to this socket. Or, directly from the docs:
After a client has successfully joined a channel, incoming events from the client are routed through the channel's
handle_in/3callbacks. Within these callbacks, you can perform any action. Typically you'll either forward a message to all listeners withbroadcast!/3, or push a message directly down the socket withpush/3. Incoming callbacks must return thesocketto maintain ephemeral state.
We're also going to temporarily include a Logger.debug to log our output. Note that we're using inspect, which allows us to log data that is more complex than a string (tuples, etc). For more on built-in protocols, check the docs.
And believe it or not, that's all we need for a functioning channel. Phoenix makes it really easy to set up channels. If this has you confused, it will make more sense when we implement the frontend code to connect to the socket.
We're going to create a ChannelHelpers module and separate out the authorization logic because we're going to need to use the same logic in multiple channels. We will likely implement additional utility functions in the future, so in order to keep our code DRY and consistent we're going to keep all these functions in one place.
We're also going to introduce some inline documentation using @moduledoc and @doc. Both accept markdown and are used to automatically generate documentation. If you've ever wondered how Elixir, Phoenix, Ecto, and every other hex package has such awesome documentation, it's because people use the inline documentation to describe their functions.
The two terms are pretty self-explanatory: @moduledoc is for describing the module, while @doc is for describing a function. You should definitely look over some existing packages to see how functions are documented.
$ touch web/channels/channel_helpers.exdefmodule PhoenixChat.ChannelHelpers do @moduledoc """ Convenience functions imported in all Channels """ @doc """ Convenience function for authorization """ def authorize(payload, fun, custom_authorize \\ nil) do check_authorization = custom_authorize || &authorized?/1 if check_authorization.(payload) do fun.() else {:error, %{reason: "unauthorized"}} end end @doc """ Function that determines authorization logic. If `true`, all users will be authorized. """ def authorized?(_payload) do true endendThe authorize/2 function takes in the payload and an anonymous function. If the user passes the authorized?/1 function, run the function. If it's not clear what this function does, it will become clear when we implement it in our RoomChannel. If it fails the authorized? tests, then we return an :error with unauthorized.
We've also set up authorize/3, which takes in three arguments. If we so choose, we can pass in a custom_authorize override that will override the authorization we set up in authorized?. This is useful if you have a request that has an unusual authorization method.
Recall that anonymous functions are called with an additional ., such as function.() rather than simply function(). We are noting this again because it regularly causes confusion for people new to Elixir. For a more detailed explanation as to why Elixir has different syntax for named functions and anonymous functions, check out this StackOverflow answer by Elixir creator Jose Valim.
Then, since we're going to want to access these helpers in all of our channels, we're going to import them into every channel. Within web/web.ex, you can add modules to every function of a particular type (such as channel, model, controller, etc). This should be done sparingly because every function you add here is imported into each struct and can significantly slow down your app if you're not careful.
... def channel do quote do use Phoenix.Channel alias PhoenixChat.Repo import Ecto import Ecto.Query, only: [from: 1, from: 2] import PhoenixChat.Gettext import PhoenixChat.ChannelHelpers end end ...Then we should update our RoomChannel to use these helper functions, so we'll remove the authorized?/1 function and replace the authorization conditional within our join/3 function.
defmodule PhoenixChat.RoomChannel do use PhoenixChat.Web, :channel require Logger def join("room:" <> _uid, payload, socket) do authorize(payload, fn -> {:ok, socket} end) end def handle_in("message", payload, socket) do Logger.debug "#{inspect payload}" broadcast socket, "message", payload {:noreply, socket} endendWe've changed the join function to take in both a payload and an anonymous function that returns the same thing our previous authorized?/1 function returned, which is {:ok, socket}.