feat(chat): notify message add/removal with pubsub
This commit is contained in:
@@ -2,6 +2,8 @@ defmodule SlaxWeb.ChatRoomLive do
|
||||
@moduledoc false
|
||||
use SlaxWeb, :live_view
|
||||
|
||||
require Logger
|
||||
|
||||
alias Slax.Accounts.User
|
||||
alias Slax.Chat
|
||||
alias Slax.Chat.Message
|
||||
@@ -133,6 +135,8 @@ defmodule SlaxWeb.ChatRoomLive do
|
||||
|
||||
@impl Phoenix.LiveView
|
||||
def handle_params(params, _session, socket) do
|
||||
if socket.assigns[:room], do: Chat.unsubscribe_from_room(socket.assigns.room)
|
||||
|
||||
room =
|
||||
case Map.fetch(params, "id") do
|
||||
{:ok, id} ->
|
||||
@@ -144,6 +148,8 @@ defmodule SlaxWeb.ChatRoomLive do
|
||||
|
||||
messages = Chat.list_messages_in_room(room)
|
||||
|
||||
Chat.subscribe_to_room(room)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(hide_topic?: false, page_title: "# #{room.name}", room: room)
|
||||
@@ -168,10 +174,8 @@ defmodule SlaxWeb.ChatRoomLive do
|
||||
|
||||
socket =
|
||||
case Chat.create_message(room, user, message_params) do
|
||||
{:ok, message} ->
|
||||
socket
|
||||
|> stream_insert(:messages, message)
|
||||
|> assign_message_form(Chat.change_message(%Message{}))
|
||||
{:ok, _message} ->
|
||||
assign_message_form(socket, Chat.change_message(%Message{}))
|
||||
|
||||
{:error, changeset} ->
|
||||
assign_message_form(socket, changeset)
|
||||
@@ -182,8 +186,18 @@ defmodule SlaxWeb.ChatRoomLive do
|
||||
|
||||
@impl Phoenix.LiveView
|
||||
def handle_event("delete-message", %{"id" => message_id}, socket) do
|
||||
{:ok, message} = Chat.delete_message_by_id(message_id, socket.assigns.current_user)
|
||||
Chat.delete_message_by_id(message_id, socket.assigns.current_user)
|
||||
|
||||
{:noreply, socket}
|
||||
end
|
||||
|
||||
@impl Phoenix.LiveView
|
||||
def handle_info({:new_message, message}, socket) do
|
||||
{:noreply, stream_insert(socket, :messages, message)}
|
||||
end
|
||||
|
||||
@impl Phoenix.LiveView
|
||||
def handle_info({:deleted_message, message}, socket) do
|
||||
{:noreply, stream_delete(socket, :messages, message)}
|
||||
end
|
||||
|
||||
|
Reference in New Issue
Block a user