feat(chat): add context and use it in live view

This commit is contained in:
João Paulo Dubas 2024-10-15 00:27:18 +00:00
parent fb7dff1f6f
commit 0ae441c31a
Signed by: joao.dubas
SSH Key Fingerprint: SHA256:V1mixgOGRc/YMhGx/DNkOSmJxgA2vHNrDZEk3wt/kOA
2 changed files with 27 additions and 4 deletions

23
lib/slax/chat.ex Normal file
View File

@ -0,0 +1,23 @@
defmodule Slax.Chat do
@moduledoc """
Context to handle with chat details.
"""
import Ecto.Query
alias Slax.Chat.Room
alias Slax.Repo
def get_first_room! do
query = from(r in Room, limit: 1)
Repo.one(query)
end
def get_room!(id) do
Repo.get!(Room, id)
end
def list_rooms do
Repo.all(Room)
end
end

View File

@ -2,7 +2,7 @@ defmodule SlaxWeb.ChatRoomLive do
@moduledoc false
use SlaxWeb, :live_view
alias Slax.Repo
alias Slax.Chat
alias Slax.Chat.Room
@impl Phoenix.LiveView
@ -42,7 +42,7 @@ defmodule SlaxWeb.ChatRoomLive do
@impl Phoenix.LiveView
def mount(_params, _session, socket) do
rooms = Repo.all(Room)
rooms = Chat.list_rooms()
{:ok, assign(socket, hide_topic?: false, rooms: rooms)}
end
@ -52,10 +52,10 @@ defmodule SlaxWeb.ChatRoomLive do
room =
case Map.fetch(params, "id") do
{:ok, id} ->
Repo.get(Room, id)
Chat.get_room!(id)
:error ->
List.first(socket.assigns.rooms)
Chat.get_first_room!()
end
{:noreply, assign(socket, hide_topic?: false, room: room)}