Skip to content

Commit d233a6b

Browse files
author
Sergio Arbeo
committed
Normalize params
1 parent 4a00de9 commit d233a6b

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

lib/live_view_events/notify.ex

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -154,14 +154,20 @@ defmodule LiveViewEvents.Notify do
154154
- A PID.
155155
- A tuple of the form `{Module, "id"}` to send a message to a [`LiveView.Component`](`Phoenix.LiveView.Component`) in the same process.
156156
- A tuple of the form `{pid, Module, "id"}` to send a message to a [`LiveView.Component`](`Phoenix.LiveView.Component`) in a different process.
157+
158+
The event send will take the form of `{message, %{}}`.
157159
"""
158160
def notify_to(nil, _message), do: nil
159-
def notify_to(:self, message), do: notify_to(self(), message)
160-
def notify_to(pid, message) when is_pid(pid), do: send(pid, message)
161+
def notify_to(:self, message), do: notify_to(self(), normalize_message(message))
162+
def notify_to(pid, message) when is_pid(pid), do: send(pid, normalize_message(message))
161163

162164
def notify_to(target, message) when is_tuple(target) do
163165
{pid, module, id} = process_tuple(target)
164-
Phoenix.LiveView.send_update(pid, module, %{:id => id, @assign_name_for_event => message})
166+
167+
Phoenix.LiveView.send_update(pid, module, %{
168+
:id => id,
169+
@assign_name_for_event => normalize_message(message)
170+
})
165171
end
166172

167173
@doc """
@@ -182,6 +188,9 @@ defmodule LiveViewEvents.Notify do
182188
})
183189
end
184190

191+
defp normalize_message({_message_name, %{} = _params} = message), do: message
192+
defp normalize_message(message_name), do: {message_name, %{}}
193+
185194
defp process_tuple({module, id}), do: {self(), module, id}
186195
defp process_tuple({pid, _module, _id} = target) when is_pid(pid), do: target
187196
end

test/live_view_events/notify_test.exs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,11 @@ defmodule LiveViewEvents.NotifyTest do
1010
test "notify_to/3 with `nil` target does not break" do
1111
Notify.notify_to(nil, "event", %{some: :params})
1212
end
13+
14+
test "notify_to/2 add default empty params" do
15+
Notify.notify_to(:self, "event")
16+
17+
assert_receive {"event", %{} = params}
18+
assert Enum.empty?(params)
19+
end
1320
end

0 commit comments

Comments
 (0)