feeniks/lib/plug_helpers.ex
2023-01-20 21:09:11 +02:00

39 lines
1 KiB
Elixir

defmodule PlugHelpers do
@typep plug_definition() :: {module(), term()}
@typep plug_function() :: (Plug.Conn.t() -> Plug.Conn.t())
@spec module_plug(module(), term()) :: plug_definition()
def module_plug(plug, opts \\ []) do
{plug, plug.init(opts)}
end
@spec pipeline(list()) :: [plug_definition() | plug_function()]
def pipeline(plugs) do
plugs
|> List.flatten()
|> Enum.filter(fn
{mod, _opts} when is_atom(mod) -> true
fun when is_function(fun, 1) -> true
_ -> false
end)
end
@spec run_plugs(Plug.Conn.t(), [plug_definition() | plug_function()]) ::
Plug.Conn.t()
def run_plugs(conn, plugs) do
for plug <- plugs, reduce: conn do
%Plug.Conn{halted: true} = c ->
c
%Plug.Conn{} = c ->
case plug do
p when is_function(p) -> p.(c)
{p, opts} -> p.call(c, opts)
what -> raise "Unknown plug type #{inspect(what)} in plug list"
end
other ->
"Expected plugs to return Plug.Conn, got: #{inspect(other)}"
end
end
end