I have an application that is part Raxx part Plug(Phoenix). This application has to make use of the same session. For this reason I have implemented Raxx.Session to be compatible with Plug.Session (when set up with the correct configuration).
Now I want to have test coverage that ensures the sessions are compatible.
To do this I have the same application implemented in both Raxx and Plug. It sets the session from a path param and returns the previous value that was saved in the session.
Raxx
defmodule RaxxSessionApp do
use Raxx.SimpleServer
alias Raxx.Session
def handle_request(request = %{path: ["set", value]}, state) do
{:ok, session} = Session.extract(request, state.session_config)
session = session || %{}
previous = Map.get(session, :value, "")
session = Map.put(session, :value, value)
response(:ok)
|> Session.embed(session, state.session_config)
|> set_body(previous)
end
end
Plug
defmodule PlugSessionApp do
alias Plug.Conn
alias Plug.Session
def call(conn, config) do
conn
|> set_secret(config.secret_key_base)
|> Session.call(config.session_config)
|> endpoint(nil)
end
def set_secret(conn, secret_key_base) do
%{conn | secret_key_base: secret_key_base}
end
def endpoint(conn = %{path_info: ["set", value]}, _) do
conn =
conn
|> Conn.fetch_session()
# NOTE get session transparently casts keys to strings
previous = patched_get_session(conn, :value) || ""
conn
|> Conn.put_session(:value, value)
|> Conn.send_resp(200, previous)
end
defp patched_get_session(conn, key) do
conn
|> Conn.get_session()
|> Map.get(key)
end
end
Full test code available on PR https://github.com/CrowdHailer/raxx/pull/182/files
Now this code is working this question is really for my own curiosity.
How do I implement the Plug application using Plug.Builder
and have configurable sessions?
I tried using use Plug.Builder, init_mode: :runtime
. I think understand what the point of init_mode: :runtime
is for.