/
SwaggerSupport.scala
64 lines (52 loc) · 1.87 KB
/
SwaggerSupport.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package org.http4s
package rho
package swagger
import io.swagger.util.Json
import headers.`Content-Type`
import org.http4s.rho.bits.PathAST.TypedPath
import org.http4s.rho.swagger.models.{Swagger, Info}
import shapeless._
object SwaggerSupport {
/**
* Create a RhoMiddleware adding a route to get the Swagger json file
* representing the full API
*/
def apply(
swaggerFormats: SwaggerFormats = DefaultSwaggerFormats,
apiPath: TypedPath[HNil] = "swagger.json",
apiInfo: Info = Info(title = "My API", version = "1.0.0"),
swaggerRoutesInSwagger: Boolean = false): RhoMiddleware = { routes =>
lazy val swaggerSpec: Swagger =
createSwagger(swaggerFormats, apiPath, apiInfo)(
routes ++ (if(swaggerRoutesInSwagger) swaggerRoute else Seq.empty )
)
lazy val swaggerRoute: Seq[RhoRoute[_ <: HList]] =
createSwaggerRoute(swaggerSpec, apiPath).getRoutes
routes ++ swaggerRoute
}
/**
* Create the swagger model for a set of routes
*/
def createSwagger(
swaggerFormats: SwaggerFormats = DefaultSwaggerFormats,
apiPath: TypedPath[HNil] = "swagger.json",
apiInfo: Info = Info(title = "My API", version = "1.0.0"))(routes: Seq[RhoRoute[_]]): Swagger = {
val sb = new SwaggerModelsBuilder(swaggerFormats)
routes.foldLeft(Swagger())((s, r) => sb.mkSwagger(apiInfo, r)(s))
}
/**
* Create a RhoService with the route to the Swagger json
* for the given Swagger Specification
*/
def createSwaggerRoute(
swagger: => Swagger,
apiPath: TypedPath[HNil] = "swagger.json"
): RhoService = new RhoService {
lazy val response = Ok(
Json.mapper()
.writerWithDefaultPrettyPrinter()
.writeValueAsString(swagger.toJModel)
).putHeaders(`Content-Type`(MediaType.`application/json`))
"Swagger documentation" ** GET / apiPath |>> (() => response)
}
}