{"componentChunkName":"component---src-templates-lesson-js","path":"/phoenix-chat/persist-messages-to-the-database","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\": \"Persist Messages to the Database\",\n  \"order\": 28,\n  \"free\": false,\n  \"active\": true,\n  \"tech\": [\"phoenix\", \"postgres\"]\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, \"Persist Messages to the Database\"), mdx(\"ul\", null, mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Creating a Message model\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Querying database\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Persist messages to database\"), mdx(\"li\", {\n    \"parentName\": \"ul\"\n  }, \"Unix timestamp to DateTime\")), mdx(\"p\", null, \"To keep our app simple with the functionality most people expect, we're going to persist all messages to our Postgres database. In order to do this, we need to create a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Message\"), \" model so our database knows what kind of data it's receiving.\"), mdx(\"p\", null, \"Later on, we may decide that we don't need to store these messages in a database or we may need to cache our messages in memory for better performance. If we later decide to go that route, we can use \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/getting-started/mix-otp/ets.html\",\n    \"parentName\": \"p\"\n  }, \"ETS\"), \". No need for premature optimization.\"), mdx(\"h2\", null, \"Creating the \", mdx(\"inlineCode\", {\n    \"parentName\": \"h2\"\n  }, \"Message\"), \" model\"), mdx(\"p\", null, \"We're going to use the built-in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"mix\"), \" generator to create the boilerplate for a new migration.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix phoenix.gen.model Message messages body from room \\\\\\n  timestamp:datetime user_id:references:users\\n\")), mdx(\"p\", null, \"This will create three new files, the names of which should have logged in your terminal.\"), mdx(\"p\", null, \"The first thing we should check out is our migration file to update our database with the new data type. This file should already have all the relevant fields we are interested in and we don't have to change anything.\"), mdx(\"p\", null, \"The last thing we're going to do before we persist our messages to the database is add a function that gives us the ability to limit the number of messages we receive from the database (with a default of 10).\"), mdx(\"p\", null, mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Ecto\"), \" allows us to \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/ecto/Ecto.Query.html#from/2\",\n    \"parentName\": \"p\"\n  }, \"define our queries as functions\"), \" using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"from/2\"), \", which is a really nice feature, so we're going to create a new function called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"latest_room_messages\"), \" that finds all messages from a particular room, then orders them by the most recent, and limits the number of messages.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.Message do\\n  use PhoenixChat.Web, :model\\n\\n  schema \\\"messages\\\" do\\n    field :body, :string\\n    field :timestamp, Ecto.DateTime\\n    field :room, :string\\n    field :from, :string\\n    belongs_to :user, PhoenixChat.User\\n\\n    timestamps\\n  end\\n\\n  @required_fields ~w(body timestamp room)\\n  @optional_fields ~w(user_id from)\\n\\n  @doc \\\"\\\"\\\"\\n  Creates a changeset based on the `model` and `params`.\\n  If no params are provided, an invalid changeset is returned\\n  with no validation performed.\\n  \\\"\\\"\\\"\\n  def changeset(model, params \\\\\\\\ :empty) do\\n    model\\n    |> cast(params, @required_fields, @optional_fields)\\n  end\\n\\n  @doc \\\"\\\"\\\"\\n  An `Ecto.Query` that returns the last 10 message records for a given room.\\n  \\\"\\\"\\\"\\n  def latest_room_messages(room, number \\\\\\\\ 10) do\\n    from m in __MODULE__,\\n         where: m.room ==  ^room,\\n         order_by: [desc: :timestamp],\\n         limit: ^number\\n  end\\nend\\n\")), mdx(\"p\", null, \"At this point, you should run your migration.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ mix ecto.migrate\\n\")), mdx(\"h2\", null, \"Updating our \", mdx(\"inlineCode\", {\n    \"parentName\": \"h2\"\n  }, \"RoomChannel\")), mdx(\"p\", null, \"Now we need to update our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"RoomChannel\"), \" to start using our new model.\"), mdx(\"p\", null, \"The first thing to change is our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"join/3\"), \" function. Rather than simply checking the authorization status and returning the socket, we're going to reply with a payload of message records. This way, when a client joins the channel, she automatically receives the message history.\"), mdx(\"p\", null, \"We start this function with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room_id\"), \" and pass it into the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Message.latest_room_messages/2\"), \" function we created earlier. This creates an Ecto query based on the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"room_id\"), \", which we can them pass to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Repo.all\"), \", which finds all of our data that matches the query.\"), mdx(\"p\", null, \"Then we use \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Enum.map\"), \" to format our messages in the way our client expects to receive them (explained in greater detail below the code block). Then we reverse the order to show the newest results first.\"), mdx(\"p\", null, \"Finally, we return the messages that we just created along with our socket. \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"join/3\"), \" expects \", mdx(\"a\", {\n    \"href\": \"https://hexdocs.pm/phoenix/Phoenix.Channel.html#c:join/3\",\n    \"parentName\": \"p\"\n  }, \"one of three things\"), \" as its return value: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{:ok, Phoenix.Socket.t}\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{:ok, map, Phoenix.Socket.t}\"), \", or \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{:error, map}\"), \" We were previously sending the first value, but now that we have a map to send along, we're sending the second value.\"), mdx(\"p\", null, \"We also created a private function called \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message_payload\"), \", which takes the message and formats it before returning it.\"), 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  alias PhoenixChat.{Message, Repo}\\n\\n  def join(\\\"room:\\\" <> room_id, payload, socket) do\\n    authorize(payload, fn ->\\n      messages = room_id\\n        |> Message.latest_room_messages\\n        |> Repo.all\\n        |> Enum.map(&message_payload/1)\\n        |> Enum.reverse\\n      {:ok, %{messages: messages}, socket}\\n    end)\\n  end\\n\\n  defp message_payload(message) do\\n    from = message.user_id || message.from\\n    %{body: message.body,\\n      timestamp: message.timestamp,\\n      room: message.room,\\n      from: from,\\n      id: message.id}\\n  end\\n\\n  ...\\nend\\n\")), mdx(\"p\", null, \"Note the syntax used to call \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message_payload\"), \". Using an ampersand (\", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"&\"), \") along with the arity (number of arguments) is a shorthand way of writing anonymous functions. The two functions below are equivalent.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"|> Enum.map(&message_payload/1)\\n\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"|> Enum.map(fn x -> message_payload(x) end)\\n\")), mdx(\"p\", null, \"You will see this syntax a lot in Elixir. For more, see the \", mdx(\"a\", {\n    \"href\": \"http://elixir-lang.org/crash-course.html#partials-and-function-captures-in-elixir\",\n    \"parentName\": \"p\"\n  }, \"docs\"), \".\"), mdx(\"p\", null, \"The last thing we should do before actually writing these to our database is check if the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" passed to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"UserSocket\"), \" is an administrator id or an anonymous user id.\"), mdx(\"p\", null, \"We first pull the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"id\"), \" out of the params passed to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"connect/2\"), \". Then, if that value exists \", mdx(\"em\", {\n    \"parentName\": \"p\"\n  }, \"and\"), \" we can find that user in the database, then we assign that to the value \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \".\"), mdx(\"p\", null, \"Then we assign values to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"socket\"), \" depending on whether or not \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" passed the two criteria above (exists and is in the database). If the user does exist, we assign the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \", \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"username\"), \", and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"email\"), \" to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"socket\"), \". If \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user\"), \" does not have a value, we assign the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \" to \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"nil\"), \" and give it the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \" for the anonymous user.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"  alias PhoenixChat.{Repo, User}\\n\\n  ...\\n\\n  def connect(params, socket) do\\n    user_id = params[\\\"id\\\"]\\n    user = user_id && Repo.get(User, user_id)\\n\\n    socket = if user do\\n      socket\\n        |> assign(:user_id, user_id)\\n        |> assign(:username, user.username)\\n        |> assign(:email, user.email)\\n      else\\n        socket\\n          |> assign(:user_id, nil)\\n          |> assign(:uuid, params[\\\"uuid\\\"])\\n      end\\n\\n    {:ok, socket}\\n  end\\n\")), mdx(\"p\", null, \"Now we can persist our messages to the database. The most logical place to do this is within our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"handle_in\"), \" function in the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"RoomChannel\"), \", since this is where we handle incoming messages. Rather than simply \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"broadcast\"), \" the message as we did previously, we're going to add the message to the database, then broadcast it.\"), mdx(\"h2\", null, \"Updating handle_in\"), mdx(\"p\", null, \"Once we receive an incoming connection, we add two parameters to our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"payload\"), \" from \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"socket.assigns\"), \" using \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Map.put\"), \", which adds the named key-value pair to a map: \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \" and \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"from\"), \".\"), mdx(\"p\", null, \"Then we create a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \" with the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"%Message{}\"), \" model and the payload we just updated in preparation for our database update.\"), mdx(\"p\", null, \"Then we use a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"case\"), \" statement to check if \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Repo.insert\"), \" accepts our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"changeset\"), \". If it does, it will return \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"{:ok, message}\"), \" and we should format our message with \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message_payload\"), \" and broadcast as we we did before. In the event of an error, it returns an error.\"), mdx(\"p\", null, \"The message payload sent to all client subscribers to the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"\\\"message\\\"\"), \" event and includes a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"from\"), \" field. This \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"from\"), \" is used to identify who sent the message and is either a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \" or a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \". If a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"uuid\"), \", then user is anonymous; if a \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"user_id\"), \", the user is an admin.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"def handle_in(\\\"message\\\", payload, socket) do\\n  payload = payload\\n    |> Map.put(\\\"user_id\\\", socket.assigns.user_id)\\n    |> Map.put(\\\"from\\\", socket.assigns[:uuid])\\n  changeset = Message.changeset(%Message{}, payload)\\n\\n  case Repo.insert(changeset) do\\n    {:ok, message} ->\\n      payload = message_payload(message)\\n      broadcast! socket, \\\"message\\\", payload\\n      {:reply, :ok, socket}\\n    {:error, changeset} ->\\n      {:reply, {:error, %{errors: changeset}}, socket}\\n  end\\nend\\n\")), mdx(\"h2\", null, \"Unix timestamp to DateTime\"), mdx(\"p\", null, \"Since we're receiving all of our timestamps from JavaScript, the time is going to be in milliseconds since January 1, 1970, which is a different format than Ecto.DateTime expects. Because of this disparity, we're going to create a small module to handle this for us.\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-bash\",\n    \"parentName\": \"pre\"\n  }, \"$ touch lib/phoenix_chat/date_time.ex\\n\")), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"defmodule PhoenixChat.DateTime do\\n  @behaviour Ecto.Type\\n\\n  def type(), do: :datetime\\n\\n  def cast(milliseconds) when is_integer(milliseconds) do\\n    with {:ok, datetime} <- DateTime.from_unix(milliseconds, :milliseconds),\\n         {:ok, ecto_datetime} <- Ecto.DateTime.cast(datetime),\\n         do: {:ok, ecto_datetime}\\n  end\\n\\n  def cast(value) do\\n    Ecto.DateTime.cast(value)\\n  end\\n\\n  def load(value) do\\n    Ecto.DateTime.load(value)\\n  end\\n\\n  def dump(value) do\\n    Ecto.DateTime.dump(value)\\n  end\\nend\\n\")), mdx(\"p\", null, \"Then we need to change our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"Message\"), \" model to use our \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"PhoenixChat.DateTime\"), \" module in \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"message.ex\"), \".\"), mdx(\"pre\", null, mdx(\"code\", {\n    \"className\": \"language-elixir\",\n    \"parentName\": \"pre\"\n  }, \"...\\n  schema \\\"messages\\\" do\\n    field :body, :string\\n    field :timestamp, PhoenixChat.DateTime\\n    field :room, :string\\n    field :from, :string\\n    belongs_to :user, PhoenixChat.User\\n\\n    timestamps\\n  end\\n...\\n\")), mdx(\"p\", null, \"And now we have message persistence to our Postgres database. You'll also notice that when write messages in your \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"phoenix-chat\"), \" component, the messages will appear on the correct side. That's because we're now passing in the \", mdx(\"inlineCode\", {\n    \"parentName\": \"p\"\n  }, \"from\"), \" field, which our component is using to determine on which side the messages displays.\"));\n}\n;\nMDXContent.isMDXComponent = true;","excerpt":"Persist Messages to the Database Creating a Message model Querying database Persist messages to database Unix timestamp to DateTime To keep…","frontmatter":{"title":"Persist Messages to the Database","order":28,"active":true,"free":false,"tech":["phoenix","postgres"]}}},"pageContext":{"slug":"persist-messages-to-the-database","prevNode":{"frontmatter":{"title":"Use Presence to List Active Users","active":true,"free":false,"order":27,"tech":["phoenix"]},"fields":{"slug":"use-presence-to-list-active-users"}},"nextNode":{"frontmatter":{"title":"Create Anonymous User Model","active":true,"free":false,"order":29,"tech":["phoenix"]},"fields":{"slug":"create-anonymous-user-model"}}}},"staticQueryHashes":["1723017916"]}