Skip to content

Commit

Permalink
Fix 'not-found' error key in test mode
Browse files Browse the repository at this point in the history
Possible issue:
All session keys in a Plug.Conn get turned into strings, so there's
no way to setup the maybe_subscribe/2 for success in a test environment.

Issue ref:
pentacent#13
  • Loading branch information
Olaleye-Blessing committed Mar 29, 2023
1 parent ce93852 commit 5d015ab
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions lib/phoenix_live_session.ex
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ defmodule PhoenixLiveSession do

defp put_meta(data, sid, opts) do
data
|> Map.put(:__sid__, sid)
|> Map.put(:__opts__, opts)
|> Map.put("__sid__", sid)
|> Map.put("__opts__", opts)
end

defp maybe_clean(opts) do
Expand Down Expand Up @@ -225,20 +225,19 @@ defmodule PhoenixLiveSession do
"""
@spec maybe_subscribe(Phoenix.LiveView.Socket.t(), Plug.Session.Store.session()) ::
Phoenix.LiveView.Socket.t()
def maybe_subscribe(socket, session) do
def maybe_subscribe(socket, %{"__sid__" => sid, "__opts__" => opts}) do
if LiveView.connected?(socket) do
sid = Map.fetch!(session, :__sid__)
opts = Map.fetch!(session, :__opts__)
pub_sub = Keyword.fetch!(opts, :pub_sub)
channel = "live_session:#{sid}"
PubSub.subscribe(pub_sub, channel)
PubSub.subscribe(pub_sub, "live_session:#{sid}")

put_in(socket.private[:live_session], id: sid, opts: opts)
else
socket
end
end

def maybe_subscribe(socket, _), do: socket

@doc """
This function can be called in two ways:any()
Expand All @@ -253,8 +252,8 @@ defmodule PhoenixLiveSession do
from the `mount/3` callback directly in this function.
Retrieves and returns updated session data.
"""
@spec put_session(Phoenix.LiveView.Socket.t(), String.t() | atom(), term()) ::
Phoenix.LiveView.Socket.t()
@spec put_session(Phoenix.LiveView.Socket.t() | map(), String.t() | atom(), term()) ::
Phoenix.LiveView.Socket.t() | %{}
def put_session(%Phoenix.LiveView.Socket{} = socket, key, value) do
sid = get_in(socket.private, [:live_session, :id])
opts = get_in(socket.private, [:live_session, :opts])
Expand All @@ -263,8 +262,7 @@ defmodule PhoenixLiveSession do
socket
end

@spec put_session(%{__sid__: String.t(), __opts__: list()}, String.t() | atom(), term()) :: %{}
def put_session(%{__sid__: sid, __opts__: opts}, key, value) do
def put_session(%{"__sid__" => sid, "__opts__" => opts}, key, value) do
put_in(sid, to_string(key), value, opts)

get(nil, sid, opts)
Expand Down

0 comments on commit 5d015ab

Please sign in to comment.