{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/set-up-phoenix-channels","result":{"data":{"mdx":{"body":"function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n/* @jsx mdx */\nvar _frontmatter = {\n  \"title\": \"Set Up Phoenix Channels\",\n  \"order\": 25,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\"]\n};\n\nvar makeShortcode = function makeShortcode(name) {\n  return function MDXDefaultShortcode(props) {\n    console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n    return mdx(\"div\", props);\n  };\n};\n\nvar layoutProps = {\n  _frontmatter: _frontmatter\n};\nvar MDXLayout = \"wrapper\";\nreturn function MDXContent(_ref) {\n  var components = _ref.components,\n      props = _objectWithoutProperties(_ref, [\"components\"]);\n\n  return mdx(MDXLayout, _extends({}, layoutProps, props, {\n    components: components,\n    mdxType: \"MDXLayout\"\n  }), mdx(\"h1\", null, \"Set up Phoenix Channels\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Setting up a \", mdx(\"inlineCode\", {\n    \"parentName\": \"li\"\n  }, \"room\"), \" channel\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Extracting authorization\")), mdx(\"p\", null, \"Now 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.\"), mdx(\"p\", null, \"If you're familiar with a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"socket\"), \", you'll pick up \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"channels\"), \" fairly quickly. If you're not familiar with the concept of \", mdx(\"a\", {\n    \"href\": \"https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API\",\n    \"parentName\": \"p\"\n  }, \"websockets\"), \", it's best to think of the internet as split between two types of connections: 1) request-response, and 2) sockets.\"), mdx(\"p\", null, \"Request-response is how we're handling our JSON web token. Each time you send a request, the connection (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"conn\"), \") is essentially a new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"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.\"), mdx(\"p\", null, \"What's more, a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"channel\"), \" can be stateful, meaning when we connect to a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"If this sounds complicated or magical, it should make more sense when we start to implement it.\"), mdx(\"h2\", null, \"Setting up a \", mdx(\"inlineCode\", {\n    \"parentName\": \"h2\"\n  }, \"room\"), \" channel\"), mdx(\"p\", null, \"Based on the way our app works, we're going to create a new \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room\"), \" for each of our anonymous customers and list them in the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"We're going to use the built-in generator to create our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room\"), \" channel. Remember, you can run \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix --help\"), \" to see all the built-in functions you can run with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.gen.channel Room\\n\")), mdx(\"p\", null, \"Then (as it says in the console output), we want to add that \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"channel\"), \" to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, \"We're also going to use the \", mdx(\"a\", {\n    \"href\": \"http://www.phoenixframework.org/docs/channels#section-socket-assigns\",\n    \"parentName\": \"p\"\n  }, mdx(\"inlineCode\", {\n    \"parentName\": \"a\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"assign\"), \" as a way to pass values to other parts of the app on the socket struct/object.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.UserSocket do\\n  use Phoenix.Socket\\n\\n  ## Channels\\n  channel \\\"room:*\\\", PhoenixChat.RoomChannel\\n  ...\\n\\n  def connect(params, socket) do\\n    socket = socket\\n      |> assign(:user_id, params[\\\"id\\\"])\\n      |> assign(:username, params[\\\"username\\\"])\\n      |> assign(:email, params[\\\"email\\\"])\\n      |> assign(:uuid, params[\\\"uuid\\\"])\\n    {:ok, socket}\\n  end\\n\\n  ...\\n\")), mdx(\"p\", null, \"Then we need to handle incoming messages, so within \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room_channel.ex\"), \", add the following (with explanation below the code).\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.RoomChannel do\\n  use PhoenixChat.Web, :channel\\n  require Logger\\n\\n  def join(\\\"room:\\\" <> _uid, payload, socket) do\\n    if authorized?(payload) do\\n      {:ok, socket}\\n    else\\n      {:error, %{reason: \\\"unauthorized\\\"}}\\n    end\\n  end\\n\\n  def handle_in(\\\"message\\\", payload, socket) do\\n    Logger.debug \\\"#{inspect payload}\\\"\\n    broadcast socket, \\\"message\\\", payload\\n    {:noreply, socket}\\n  end\\n\\n  ...\\n\")), mdx(\"p\", null, \"First, we're adding a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"join\"), \" request starts with the pattern \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room:\"), \" with anything following (other than \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room:lobby\"), \" from the boilerplate code), the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"join\"), \" that we defined will get called.\"), mdx(\"p\", null, \"If we get a pattern that matches, we check to see if the user is authorized. The current \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"p\", null, mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"Note: in Elixir, question marks (\", mdx(\"inlineCode\", {\n    \"parentName\": \"em\"\n  }, \"?\"), \") are valid characters in function names.\")), mdx(\"p\", null, \"The next function we're adding is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message\"), \" (which is an arbitrary title; you could name it whatever you want) then \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"broadcast\"), \" that message to everything on the frontend that is currently listening to this socket. Or, directly from the \", mdx(\"a\", {\n    \"href\": \"https://github.com/phoenixframework/phoenix/blob/master/lib/phoenix/channel.ex\",\n    \"parentName\": \"p\"\n  }, \"docs\"), \":\"), mdx(\"blockquote\", null, mdx(\"p\", {\n    \"parentName\": \"blockquote\"\n  }, \"After a client has successfully joined a channel, incoming events from the client are routed through the channel's \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handle_in/3\"), \" callbacks. Within these callbacks, you can perform any action. Typically you'll either forward a message to all listeners with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"broadcast!/3\"), \", or push a message directly down the socket with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"push/3\"), \". Incoming callbacks must return the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"socket\"), \" to maintain ephemeral state.\")), mdx(\"p\", null, \"We're also going to temporarily include a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Logger.debug\"), \" to log our output. Note that we're using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"inspect\"), \", which allows us to log data that is more complex than a string (tuples, etc). For more on built-in protocols, check the \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/getting-started/protocols.html#built-in-protocols\",\n    \"parentName\": \"p\"\n  }, \"docs\"), \".\"), mdx(\"p\", null, \"And believe it or not, that's all we need for a functioning channel. Phoenix makes it really easy to set up \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"channels\"), \". If this has you confused, it will make more sense when we implement the frontend code to connect to the socket.\"), mdx(\"h2\", null, \"Extracting authorization\"), mdx(\"p\", null, \"We're going to create a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"a\", {\n    \"href\": \"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\",\n    \"parentName\": \"p\"\n  }, \"DRY\"), \" and consistent we're going to keep all these functions in one place.\"), mdx(\"p\", null, \"We're also going to introduce some inline documentation using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@moduledoc\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@doc\"), \". Both accept \", mdx(\"a\", {\n    \"href\": \"https://daringfireball.net/projects/markdown/\",\n    \"parentName\": \"p\"\n  }, \"markdown\"), \" and are used to automatically generate documentation. If you've ever wondered how \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/docs/stable/elixir/Kernel.html\",\n    \"parentName\": \"p\"\n  }, \"Elixir\"), \", \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.html\",\n    \"parentName\": \"p\"\n  }, \"Phoenix\"), \", \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.html\",\n    \"parentName\": \"p\"\n  }, \"Ecto\"), \", and \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/voodoo_mfg/api-reference.html\",\n    \"parentName\": \"p\"\n  }, \"every\"), \" \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/stripity_stripe/extra-api-reference.html\",\n    \"parentName\": \"p\"\n  }, \"other\"), \" hex package has such awesome documentation, it's because people use the inline documentation to describe their functions.\"), mdx(\"p\", null, \"The two terms are pretty self-explanatory: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@moduledoc\"), \" is for describing the module, while \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"@doc\"), \" is for describing a function. You should definitely look over some existing packages to see how functions are documented.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch web/channels/channel_helpers.ex\\n\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.ChannelHelpers do\\n  @moduledoc \\\"\\\"\\\"\\n  Convenience functions imported in all Channels\\n  \\\"\\\"\\\"\\n\\n  @doc \\\"\\\"\\\"\\n  \\b\\bConvenience function for authorization\\n  \\\"\\\"\\\"\\n  def authorize(payload, fun, custom_authorize \\\\\\\\ nil) do\\n    check_authorization = custom_authorize || &authorized?/1\\n    if check_authorization.(payload) do\\n      fun.()\\n    else\\n      {:error, %{reason: \\\"unauthorized\\\"}}\\n    end\\n  end\\n\\n  @doc \\\"\\\"\\\"\\n  \\b\\bFunction that determines authorization logic. If `true`, all users will be authorized.\\n  \\\"\\\"\\\"\\n  def authorized?(_payload) do\\n    true\\n  end\\nend\\n\")), mdx(\"p\", null, \"The \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorize/2\"), \" function takes in the payload and an anonymous function. If the user passes the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"RoomChannel\"), \". If it fails the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorized?\"), \" tests, then we return an \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \":error\"), \" with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"unauthorized\"), \".\"), mdx(\"p\", null, \"We've also set up \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorize/3\"), \", which takes in three arguments. If we so choose, we can pass in a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"custom_authorize\"), \" override that will override the authorization we set up in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorized?\"), \". This is useful if you have a request that has an unusual authorization method.\"), mdx(\"p\", null, \"Recall that anonymous functions are called with an additional \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \".\"), \", such as \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"function.()\"), \" rather than simply \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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 \", mdx(\"a\", {\n    \"href\": \"http://stackoverflow.com/questions/18011784/why-are-there-two-kinds-of-functions-in-elixir\",\n    \"parentName\": \"p\"\n  }, \"StackOverflow answer\"), \" by Elixir creator Jose Valim.\"), mdx(\"p\", null, \"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 \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"web/web.ex\"), \", you can add modules to every function of a particular type (such as \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"channel\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"model\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"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.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  ...\\n\\n  def channel do\\n    quote do\\n      use Phoenix.Channel\\n\\n      alias PhoenixChat.Repo\\n      import Ecto\\n      import Ecto.Query, only: [from: 1, from: 2]\\n      import PhoenixChat.Gettext\\n      import PhoenixChat.ChannelHelpers\\n    end\\n  end\\n\\n  ...\\n\")), mdx(\"p\", null, \"Then we should update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"RoomChannel\"), \" to use these helper functions, so we'll remove the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorized?/1\"), \" function and replace the authorization conditional within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"join/3\"), \" function.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.RoomChannel do\\n  use PhoenixChat.Web, :channel\\n  require Logger\\n\\n  def join(\\\"room:\\\" <> _uid, payload, socket) do\\n    authorize(payload, fn ->\\n      {:ok, socket}\\n    end)\\n  end\\n\\n  def handle_in(\\\"message\\\", payload, socket) do\\n    Logger.debug \\\"#{inspect payload}\\\"\\n    broadcast socket, \\\"message\\\", payload\\n    {:noreply, socket}\\n  end\\nend\\n\")), mdx(\"p\", null, \"We've changed the join function to take in both a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"payload\"), \" and an anonymous function that returns the same thing our previous \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"authorized?/1\"), \" function returned, which is \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{:ok, socket}\"), \".\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Set up Phoenix Channels Setting up a  room  channel Extracting authorization Now that we have a user interface in place to send and receive…","frontmatter":{"title":"Set Up Phoenix Channels","order":25,"active":true,"free":false,"tech":["phoenix"]}}},"pageContext":{"slug":"set-up-phoenix-channels","prevNode":{"frontmatter":{"title":"NPM Package for a React Component: Part 2","active":true,"free":false,"order":24,"tech":["react","npm"]},"fields":{"slug":"npm-package-for-a-react-component-part-2"}},"nextNode":{"frontmatter":{"title":"Connect React to Channels","active":true,"free":false,"order":26,"tech":["react","phoenix"]},"fields":{"slug":"connect-react-to-channels"}}}},"staticQueryHashes":["1723017916"]}