Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Runtime configuration for SwaggerUI plug #494

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions lib/open_api_spex/plug/swagger_ui.ex
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,28 @@ defmodule OpenApiSpex.Plug.SwaggerUI do
resources "/users", MyAppWeb.UserController, only: [:index, :create, :show]
get "/openapi", OpenApiSpex.Plug.RenderSpec, :show
end

## Runtime Configuration

SwaggerUI also accepts functions as parameters, allowing runtime configurations.
Because of limitations of `router.ex` file, the functions can be defined only as: `{module, function_name}`.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The SwaggerUI module is a Plug, it can be used even by a non-phoenix app specifying its routes in a router.ex.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah my bad, I will update the documentation.


## Example

defmodule RuntimeConfig do
def on_complete do
"function() { ui.preauthorizeApiKey("bearer", "your generated token here"); }"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please escape double quotes or use the ~S sigil.

end
end

scope "/" do
pipe_through :browser # Use the default browser stack

get "/swaggerui", OpenApiSpex.Plug.SwaggerUI,
path: "/api/openapi",
on_complete: {RuntimeConfig, :on_complete}
end

"""
@behaviour Plug

Expand Down Expand Up @@ -153,6 +175,7 @@ defmodule OpenApiSpex.Plug.SwaggerUI do
def call(conn, config) do
csrf_token = Plug.CSRFProtection.get_csrf_token()
config = supplement_config(config, conn)
config = evaluate_runtime_config(config)
html = render(config, csrf_token)

conn
Expand Down Expand Up @@ -203,4 +226,16 @@ defmodule OpenApiSpex.Plug.SwaggerUI do
defp supplement_config(config, _conn) do
config
end

defp evaluate_runtime_config(config) do
Enum.into(config, %{}, fn opt -> evaluate_opt(opt) end)
end

defp evaluate_opt({key, {module, function_name}}) when is_atom(module) and is_atom(function_name) do
{key, apply(module, function_name, [])}
end

defp evaluate_opt(opt) do
opt
end
end