Skip to content

Commit

Permalink
Normalize params
Browse files Browse the repository at this point in the history
  • Loading branch information
Serabe committed May 16, 2024
1 parent 4a00de9 commit d233a6b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
15 changes: 12 additions & 3 deletions lib/live_view_events/notify.ex
Original file line number Diff line number Diff line change
Expand Up @@ -154,14 +154,20 @@ defmodule LiveViewEvents.Notify do
- A PID.
- A tuple of the form `{Module, "id"}` to send a message to a [`LiveView.Component`](`Phoenix.LiveView.Component`) in the same process.
- A tuple of the form `{pid, Module, "id"}` to send a message to a [`LiveView.Component`](`Phoenix.LiveView.Component`) in a different process.
The event send will take the form of `{message, %{}}`.
"""
def notify_to(nil, _message), do: nil
def notify_to(:self, message), do: notify_to(self(), message)
def notify_to(pid, message) when is_pid(pid), do: send(pid, message)
def notify_to(:self, message), do: notify_to(self(), normalize_message(message))
def notify_to(pid, message) when is_pid(pid), do: send(pid, normalize_message(message))

def notify_to(target, message) when is_tuple(target) do
{pid, module, id} = process_tuple(target)
Phoenix.LiveView.send_update(pid, module, %{:id => id, @assign_name_for_event => message})

Phoenix.LiveView.send_update(pid, module, %{
:id => id,
@assign_name_for_event => normalize_message(message)
})
end

@doc """
Expand All @@ -182,6 +188,9 @@ defmodule LiveViewEvents.Notify do
})
end

defp normalize_message({_message_name, %{} = _params} = message), do: message
defp normalize_message(message_name), do: {message_name, %{}}

defp process_tuple({module, id}), do: {self(), module, id}
defp process_tuple({pid, _module, _id} = target) when is_pid(pid), do: target
end
7 changes: 7 additions & 0 deletions test/live_view_events/notify_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,11 @@ defmodule LiveViewEvents.NotifyTest do
test "notify_to/3 with `nil` target does not break" do
Notify.notify_to(nil, "event", %{some: :params})
end

test "notify_to/2 add default empty params" do
Notify.notify_to(:self, "event")

assert_receive {"event", %{} = params}
assert Enum.empty?(params)
end
end

0 comments on commit d233a6b

Please sign in to comment.