Skip to content
This repository has been archived by the owner on Sep 3, 2023. It is now read-only.

Commit

Permalink
handle empty array
Browse files Browse the repository at this point in the history
  • Loading branch information
meppu committed Jul 4, 2023
1 parent 15f5f5c commit 7b416e3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ To subscribe to one or more users, make use of the `subscribe` event:
}
```

By doing so, you will receive real-time updates for the specified users within the `ids` array.
By doing so, you will receive real-time updates for the specified users within the `ids` array. If the `ids` is an empty list (`[]`) or `null`, it will unsubscribe from all the subscriptions without returning anything.

To update subscribers, resend the same data with the updated `ids` value.

Expand Down
28 changes: 17 additions & 11 deletions lib/revard/gateway/listener.ex
Original file line number Diff line number Diff line change
Expand Up @@ -48,20 +48,33 @@ defmodule Revard.Gateway.Listener do
{:ok, state}
end

defp match_message(%{"event" => "subscribe", "ids" => nil}, state) do
# Unsubscribe all
Enum.each(state, &Phoenix.PubSub.unsubscribe(@pubsub, &1))

{:ok, []}
end

defp match_message(%{"event" => "subscribe", "ids" => []} = message, state) do
message
|> Map.put("ids", nil)
|> match_message(state)
end

defp match_message(%{"event" => "subscribe", "ids" => ids}, state) when is_list(ids) do
# Check format
if Enum.all?(ids, &check_id/1) do
# Unsubscribe all
Enum.each(state, &Phoenix.PubSub.unsubscribe(@pubsub, &1))

# Subscribe given ones
Enum.each(ids, &Phoenix.PubSub.subscribe(@pubsub, &1))

# Debug message
Logger.debug(
"Connection #{inspect(self())} subscribed to following id(s): #{inspect(ids)} (socket)"
"Connection #{inspect(self())} subscribing to following id(s): #{inspect(ids)} (socket)"
)

# Subscribe given ones
Enum.each(ids, &Phoenix.PubSub.subscribe(@pubsub, &1))

# Reply with initial message
initial_message =
%{type: "init", data: Revard.Storage.Users.get(ids)}
Expand All @@ -73,13 +86,6 @@ defmodule Revard.Gateway.Listener do
end
end

defp match_message(%{"event" => "subscribe", "ids" => nil}, state) do
# Unsubscribe all
Enum.each(state, &Phoenix.PubSub.unsubscribe(@pubsub, &1))

{:ok, []}
end

defp match_message(_message, state) do
invalid_payload_error(state)
end
Expand Down

0 comments on commit 7b416e3

Please sign in to comment.