-
Notifications
You must be signed in to change notification settings - Fork 412
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
SwaggerUI utility for creating routes that serve openapi (#2494)
- Loading branch information
Showing
6 changed files
with
206 additions
and
32 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
104 changes: 104 additions & 0 deletions
104
zio-http/src/main/scala/zio/http/endpoint/openapi/SwaggerUI.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
package zio.http.endpoint.openapi | ||
|
||
import java.net.URLEncoder | ||
|
||
import zio.http._ | ||
import zio.http.codec.PathCodec | ||
|
||
object SwaggerUI { | ||
|
||
val DefaultSwaggerUIVersion: String = "5.10.3" | ||
|
||
//format: off | ||
/** | ||
* Creates routes for serving the Swagger UI at the given path. | ||
* | ||
* Example: | ||
* {{{ | ||
* val routes: Routes[Any, Response] = ??? | ||
* val openAPIv1: OpenAPI = ??? | ||
* val openAPIv2: OpenAPI = ??? | ||
* val swaggerUIRoutes = SwaggerUI.routes("docs" / "openapi", openAPIv1, openAPIv2) | ||
* val routesWithSwagger = routes ++ swaggerUIRoutes | ||
* }}} | ||
* | ||
* With this middleware in place, a request to `https://www.domain.com/[path]` | ||
* would serve the Swagger UI. The different OpenAPI specifications are served | ||
* at `https://www.domain.com/[path]/[title].json`. Where `title` is the title | ||
* of the OpenAPI specification and is url encoded. | ||
*/ | ||
//format: on | ||
def routes(path: PathCodec[Unit], api: OpenAPI, apis: OpenAPI*): Routes[Any, Response] = { | ||
routes(path, DefaultSwaggerUIVersion, api, apis: _*) | ||
} | ||
|
||
//format: off | ||
/** | ||
* Creates a middleware for serving the Swagger UI at the given path and with | ||
* the given swagger ui version. | ||
* | ||
* Example: | ||
* {{{ | ||
* val routes: Routes[Any, Response] = ??? | ||
* val openAPIv1: OpenAPI = ??? | ||
* val openAPIv2: OpenAPI = ??? | ||
* val swaggerUIRoutes = SwaggerUI.routes("docs" / "openapi", openAPIv1, openAPIv2) | ||
* val routesWithSwagger = routes ++ swaggerUIRoutes | ||
* }}} | ||
* | ||
* With this middleware in place, a request to `https://www.domain.com/[path]` | ||
* would serve the Swagger UI. The different OpenAPI specifications are served | ||
* at `https://www.domain.com/[path]/[title].json`. Where `title` is the title | ||
* of the OpenAPI specification and is url encoded. | ||
*/ | ||
//format: on | ||
def routes(path: PathCodec[Unit], version: String, api: OpenAPI, apis: OpenAPI*): Routes[Any, Response] = { | ||
import zio.http.template._ | ||
val basePath = Method.GET / path | ||
val jsonRoutes = (api +: apis).map { api => | ||
basePath / s"${URLEncoder.encode(api.info.title, Charsets.Utf8.name())}.json" -> handler { (_: Request) => | ||
Response.json(api.toJson) | ||
} | ||
} | ||
val jsonPaths = jsonRoutes.map(_.routePattern.pathCodec.render) | ||
val jsonTitles = (api +: apis).map(_.info.title) | ||
val jsonUrls = jsonTitles.zip(jsonPaths).map { case (title, path) => s"""{url: "$path", name: "$title"}""" } | ||
val uiRoute = basePath -> handler { (_: Request) => | ||
Response.html( | ||
html( | ||
head( | ||
meta(charsetAttr := "utf-8"), | ||
meta(nameAttr := "viewport", contentAttr := "width=device-width, initial-scale=1"), | ||
meta(nameAttr := "description", contentAttr := "SwaggerUI"), | ||
title("SwaggerUI"), | ||
link(relAttr := "stylesheet", href := s"https://unpkg.com/swagger-ui-dist@$version/swagger-ui.css"), | ||
link( | ||
relAttr := "icon", | ||
typeAttr := "image/png", | ||
href := s"https://unpkg.com/swagger-ui-dist@$version/favicon-32x32.png", | ||
), | ||
), | ||
body( | ||
div(id := "swagger-ui"), | ||
script(srcAttr := s"https://unpkg.com/swagger-ui-dist@$version/swagger-ui-bundle.js"), | ||
script(srcAttr := s"https://unpkg.com/swagger-ui-dist@$version/swagger-ui-standalone-preset.js"), | ||
Dom.raw(s"""<script> | ||
|window.onload = () => { | ||
| window.ui = SwaggerUIBundle({ | ||
| urls: ${jsonUrls.mkString("[\n", ",\n", "\n]")}, | ||
| dom_id: '#swagger-ui', | ||
| presets: [ | ||
| SwaggerUIBundle.presets.apis, | ||
| SwaggerUIStandalonePreset | ||
| ], | ||
| layout: "StandaloneLayout", | ||
| }); | ||
|}; | ||
|</script>""".stripMargin), | ||
), | ||
), | ||
) | ||
} | ||
Routes.fromIterable(jsonRoutes) :+ uiRoute | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
67 changes: 67 additions & 0 deletions
67
zio-http/src/test/scala/zio/http/endpoint/openapi/SwaggerUISpec.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
package zio.http.endpoint.openapi | ||
|
||
import zio._ | ||
import zio.test._ | ||
|
||
import zio.http._ | ||
import zio.http.codec.HttpCodec.query | ||
import zio.http.codec.PathCodec.path | ||
import zio.http.endpoint.Endpoint | ||
|
||
object SwaggerUISpec extends ZIOSpecDefault { | ||
|
||
override def spec: Spec[TestEnvironment with Scope, Any] = | ||
suite("SwaggerUI")( | ||
test("should return the swagger ui page") { | ||
val getUser = Endpoint(Method.GET / "users" / int("userId")).out[Int] | ||
|
||
val getUserRoute = getUser.implement { Handler.fromFunction[Int] { id => id } } | ||
|
||
val getUserPosts = | ||
Endpoint(Method.GET / "users" / int("userId") / "posts" / int("postId")) | ||
.query(query("name")) | ||
.out[List[String]] | ||
|
||
val getUserPostsRoute = | ||
getUserPosts.implement[Any] { | ||
Handler.fromFunctionZIO[(Int, Int, String)] { case (id1: Int, id2: Int, query: String) => | ||
ZIO.succeed(List(s"API2 RESULT parsed: users/$id1/posts/$id2?name=$query")) | ||
} | ||
} | ||
|
||
val openAPIv1 = OpenAPIGen.fromEndpoints(title = "Endpoint Example", version = "1.0", getUser, getUserPosts) | ||
val openAPIv2 = | ||
OpenAPIGen.fromEndpoints(title = "Another Endpoint Example", version = "2.0", getUser, getUserPosts) | ||
|
||
val routes = | ||
Routes(getUserRoute, getUserPostsRoute) ++ SwaggerUI.routes("docs" / "openapi", openAPIv1, openAPIv2) | ||
|
||
val response = routes.apply(Request(method = Method.GET, url = url"/docs/openapi")) | ||
|
||
val expectedHtml = | ||
"""<!DOCTYPE html><html><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><meta name="description" content="SwaggerUI"/><title>SwaggerUI</title><link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.10.3/swagger-ui.css"/><link rel="icon" type="image/png" href="https://unpkg.com/swagger-ui-dist@5.10.3/favicon-32x32.png"/></head><body><div id="swagger-ui"></div><script src="https://unpkg.com/swagger-ui-dist@5.10.3/swagger-ui-bundle.js"></script><script src="https://unpkg.com/swagger-ui-dist@5.10.3/swagger-ui-standalone-preset.js"></script><script> | ||
|window.onload = () => { | ||
| window.ui = SwaggerUIBundle({ | ||
| urls: [ | ||
|{url: "/docs/openapi/Endpoint+Example.json", name: "Endpoint Example"}, | ||
|{url: "/docs/openapi/Another+Endpoint+Example.json", name: "Another Endpoint Example"} | ||
|], | ||
| dom_id: '#swagger-ui', | ||
| presets: [ | ||
| SwaggerUIBundle.presets.apis, | ||
| SwaggerUIStandalonePreset | ||
| ], | ||
| layout: "StandaloneLayout", | ||
| }); | ||
|}; | ||
|</script></body></html>""".stripMargin | ||
|
||
for { | ||
res <- response | ||
body <- res.body.asString | ||
} yield { | ||
assertTrue(body == expectedHtml) | ||
} | ||
}, | ||
) | ||
} |