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

Open api parser #123

Merged
merged 2 commits into from
Aug 1, 2019
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ lazy val commonSettings = Seq(
"io.circe" %% "circe-testing" % V.circe % Test,
%%("cats-effect", V.catsEffect),
%%("circe-core", V.circe),
%%("circe-parser", V.circe) % Test,
%%("circe-parser", V.circe) ,
%%("scalacheck", V.scalacheck) % Test,
%%("specs2-core", V.specs2) % Test,
%%("specs2-scalacheck", V.specs2) % Test,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -319,15 +319,15 @@ object JsonDecoders {
openapi: String,
info: Info,
servers: Option[List[Server]],
paths: Map[String, Path.ItemObject[A]],
paths: Option[Map[String, Path.ItemObject[A]]],
components: Option[Components[A]],
tags: Option[List[Tag]],
externalDocs: Option[ExternalDocs]) =>
OpenApi(
openapi,
info,
servers.getOrElse(List.empty),
paths,
paths.getOrElse(Map.empty),
components,
tags.getOrElse(List.empty),
externalDocs))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright 2018-2019 47 Degrees, LLC. <http://www.47deg.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package higherkindness.skeuomorph.openapi

import java.io.File

import qq.droste._
import higherkindness.skeuomorph.Parser
import schema.OpenApi
import cats.effect.Sync
import cats.syntax.flatMap._
import cats.syntax.functor._
import cats.syntax.either._

object ParseOpenApi {
import JsonDecoders._

case class YamlSource(file: File)
case class JsonSource(file: File)

implicit def parseYamlOpenApi[F[_], T](implicit T: Embed[JsonSchemaF, T]): Parser[F, YamlSource, OpenApi[T]] =
new Parser[F, YamlSource, OpenApi[T]] {
import yaml.{Decoder => _, _}
override def parse(input: YamlSource)(implicit S: Sync[F]): F[OpenApi[T]] =
readContent(input.file).flatMap(
x =>
S.fromEither(
yaml
.Decoder[OpenApi[T]]
.apply(x)
.left
.map(_.valueOr(identity))
)
)
}

implicit def parseJsonOpenApi[F[_], T](implicit T: Embed[JsonSchemaF, T]): Parser[F, JsonSource, OpenApi[T]] =
new Parser[F, JsonSource, OpenApi[T]] {
import io.circe.Decoder
import io.circe.parser

override def parse(input: JsonSource)(implicit S: Sync[F]): F[OpenApi[T]] =
for {
content <- readContent(input.file)
json <- S.fromEither(parser.parse(content))
openApi <- S.fromEither(Decoder[OpenApi[T]].decodeJson(json))
} yield openApi
}

private def readContent[F[_]: Sync](file: File): F[String] = Sync[F].delay {
scala.io.Source
.fromFile(file)
.getLines()
.toList
.mkString("\n")
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,15 @@ object print {
def impl[T: Basis[JsonSchemaF, ?]](
implicit http4sSpecifics: Http4sSpecifics,
codecs: Printer[Codecs]): Printer[(PackageName, OpenApi[T])] =
(sepBy(importDef, "\n") >* newLine, implDefinition[T]).contramapN {
optional(divBy(sepBy(importDef, "\n"), newLine, implDefinition[T])).contramap {
case (packageName, openApi) =>
(
packages ++ (List(
s"${packageName.show}.${TraitName(openApi).show}",
s"${packageName.show}.models._"
) ++ sumTypes(openApi).map(x => s"$x._")).map(PackageName.apply),
openApi)
openApi.paths.toList.headOption.map(
_ =>
packages ++ (List(
s"${packageName.show}.${TraitName(openApi).show}",
s"${packageName.show}.models._"
) ++ sumTypes(openApi).map(x => s"$x._")).map(PackageName.apply) ->
openApi)
}

val listEnconderPrinter: Printer[Unit] = κ(
Expand All @@ -60,7 +61,7 @@ object print {
def implDefinition[T: Basis[JsonSchemaF, ?]](
implicit http4sSpecifics: Http4sSpecifics,
codecs: Printer[Codecs]): Printer[OpenApi[T]] =
objectDef[ImplDef[T]]((
optional(objectDef[ImplDef[T]]((
κ(" def build[F[_]: Effect: Sync](client: Client[F], baseUrl: Uri)") *< κ("(implicit ") *< timeQueryParamEncoder *< κ(
")") *< κ(": ") *< show[TraitName] >* κ("[F]"),
κ(" = new ") *< show[TraitName] >* κ("[F] {") >* newLine,
Expand All @@ -71,16 +72,18 @@ object print {
twoSpaces *< twoSpaces *< optionListDecoderPrinter *< newLine *<
twoSpaces *< twoSpaces *< showQueryParamEncoder *< newLine,
sepBy(twoSpaces *< methodImpl, "\n") >* newLine *< κ(" }") *< newLine,
http4sSpecifics.applyMethod).contramapN(identity)).contramap { x =>
(
(ImplName(x).show, none),
List.empty,
(
TraitName(x),
TraitName(x),
List(PackageName(s"${TraitName(x).show}._")),
toOperationsWithPath(TraitName(x), x.paths, componentsFrom(x))._2,
TraitName(x) -> ImplName(x)))
http4sSpecifics.applyMethod).contramapN(identity))).contramap { x =>
x.paths.toList.headOption.map(
_ =>
(
(ImplName(x).show, none),
List.empty,
(
TraitName(x),
TraitName(x),
List(PackageName(s"${TraitName(x).show}._")),
toOperationsWithPath(TraitName(x), x.paths, componentsFrom(x))._2,
TraitName(x) -> ImplName(x))))
}

def successResponseImpl[T: Basis[JsonSchemaF, ?]]: Printer[Either[Response[T], Reference]] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -460,12 +460,13 @@ object print {
}

def interfaceDefinition[T: Basis[JsonSchemaF, ?]](implicit codecs: Printer[Codecs]): Printer[OpenApi[T]] =
(
sepBy(importDef, "\n") >* newLine,
κ("trait ") *< show[TraitName] >* κ("[F[_]] {") >* newLine,
space *< space *< κ("import ") *< show[TraitName] >* κ("._") >* newLine,
sepBy(method[T], "\n") >* (newLine >* κ("}") >* newLine),
objectDef(clientTypes[T] >* newLine)
).contramapN(operationsTuple[T])
optional(
(
sepBy(importDef, "\n") >* newLine,
κ("trait ") *< show[TraitName] >* κ("[F[_]] {") >* newLine,
space *< space *< κ("import ") *< show[TraitName] >* κ("._") >* newLine,
sepBy(method[T], "\n") >* (newLine >* κ("}") >* newLine),
objectDef(clientTypes[T] >* newLine)
).contramapN(operationsTuple[T])).contramap(x => x.paths.toList.headOption.map(_ => x))

}
14 changes: 9 additions & 5 deletions src/main/scala/higherkindness/skeuomorph/openapi/print.scala
Original file line number Diff line number Diff line change
Expand Up @@ -179,11 +179,15 @@ object print {
}

def model[T: Basis[JsonSchemaF, ?]](implicit codecs: Printer[Codecs]): Printer[OpenApi[T]] =
objectDef(sepBy(schemaWithName, "\n")).contramap { x =>
(
("models", none),
(List("shapeless.{:+:, CNil}", "shapeless.Coproduct") ++ sumTypes(x).map(x => s"$x._")).map(PackageName.apply),
x.components.toList.flatMap(_.schemas))
optional(objectDef(sepBy(schemaWithName, "\n"))).contramap { x =>
val models = x.components.toList.flatMap(_.schemas)
models.headOption.map(
_ =>
(
("models", none),
(List("shapeless.{:+:, CNil}", "shapeless.Coproduct") ++ sumTypes(x).map(x => s"$x._"))
.map(PackageName.apply),
x.components.toList.flatMap(_.schemas)))
}

private def sumDef(implicit codecs: Printer[Codecs]): Printer[(String, List[String])] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,29 @@ class OpenApiDecoderSpecification extends org.specs2.mutable.Specification {
}
"Open api object should be able to decode" >> {
"when required fields are provided" >> {
val json = unsafeParse("""
{
"openapi" : "3.0.0",
"info" : {
"title": "Swagger Petstore",
"version": "1.0.0"
}
}
""")

Decoder[OpenApi[JsonSchemaF.Fixed]].decodeJson(json) must beRight(
OpenApi[JsonSchemaF.Fixed](
"3.0.0",
Info("Swagger Petstore", None, "1.0.0"),
List.empty,
Map.empty,
None,
List.empty,
None
))
}

"when paths are provided" >> {
val json = unsafeParse("""
{
"openapi" : "3.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ class OpenApiPrintSpecification extends org.specs2.mutable.Specification {
import OpenApiPrintSpecification._

"models should able to print" >> {
"when not types are provided" >> {
import client.http4s.circe._
model.print(petstoreOpenApi) must ===("")
}
"when a basic type is provided" >> {
import client.http4s.circe._
model.print(petstoreOpenApi.withSchema("Foo", Fixed.string())) must
Expand Down Expand Up @@ -242,6 +246,10 @@ class OpenApiPrintSpecification extends org.specs2.mutable.Specification {

"Client trait should able to print" >> {
import client.print._
"when there are no paths" >> {
import client.http4s.circe._
interfaceDefinition.print(payloadOpenApi) must ===("")
}

"when a post operation is provided" >> {
import client.http4s.circe._
Expand Down Expand Up @@ -740,6 +748,10 @@ class OpenApiPrintSpecification extends org.specs2.mutable.Specification {

}

"when there are no paths" >> {
implDefinition.print(petstoreOpenApi) must ===("")
}

"when a put and delete are provided" >> {
implDefinition.print(petstoreOpenApi.withPath(mediaTypeReferencePutDelete)) must ===(
s"""|object PetstoreHttpClient {
Expand Down Expand Up @@ -1040,6 +1052,14 @@ class OpenApiPrintSpecification extends org.specs2.mutable.Specification {
|}""".stripMargin
)
}

"when there are no paths" >> {
import client.http4s.print.impl
import client.http4s.print.v18._
import Printer.avoid._
impl.print(PackageName("petstore") -> petstoreOpenApi) must ===("")
}

}
}

Expand Down