Skip to content

Instantly share code, notes, and snippets.

@joenoon
Created September 8, 2019 02:24
Show Gist options
  • Save joenoon/b1336bb5e6af78e3963c26bd6d7355e7 to your computer and use it in GitHub Desktop.
Save joenoon/b1336bb5e6af78e3963c26bd6d7355e7 to your computer and use it in GitHub Desktop.
defmodule MyAppWeb.LiveView.Session do
@moduledoc """
Joe Noon on 9/3/2019
LiveView does not have a direct way to change the session, but does provide a way to set flash.
The application can use `put_flash(socket, :session, %{...})`, and this plug will merge that
map when present into the persisted session.
"""
@behaviour Plug
def init(opts), do: opts
def call(conn, _) do
conn
|> handle_session()
|> handle_reset_session()
end
def handle_session(
%{
private: %{
plug_session: %{"phoenix_flash" => %{"session" => %{} = session}} = plug_session
}
} = conn
) do
conn
|> Plug.Conn.put_private(:plug_session, Map.merge(plug_session, session))
end
def handle_session(conn), do: conn
def handle_reset_session(
%{
private: %{
plug_session: %{"phoenix_flash" => %{"reset_session" => %{}} = phoenix_flash}
}
} = conn
) do
conn
|> Plug.Conn.put_private(:plug_session, %{"phoenix_flash" => phoenix_flash})
end
def handle_reset_session(conn), do: conn
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment