/** * Generated by API Builder - https://www.apibuilder.io * Service version: 1.0.1 * User agent: apibuilder app.apibuilder.io/catalystsquad/catalyst-squad-hello-world-example-api/1.0.1/http4s_0_20 */ package com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models { /** * A Hello with a name and id * * @param id The ID of the hello. * @param name The name to hello */ final case class Hello( id: _root_.java.util.UUID, name: String ) /** * A Hello that has not yet been created * * @param name The name to hello */ final case class Newhello( name: String ) } package com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models { package object json { import io.circe.Decoder._ import io.circe.Encoder._ import scala.language.implicitConversions // See below - Make Scala 2.11 Either monadic import scala.util.Try import io.circe.{Json, JsonObject, Encoder, Decoder, DecodingFailure} import io.circe.syntax._ import com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.json._ // Make Scala 2.11 Either monadic private[v1] implicit def eitherOps[A,B](e: Either[A,B]) = cats.implicits.catsSyntaxEither(e) private[v1] implicit val decodeUUID: Decoder[_root_.java.util.UUID] = Decoder.decodeString.emapTry(str => Try(_root_.java.util.UUID.fromString(str))) private[v1] implicit val encodeUUID: Encoder[_root_.java.util.UUID] = Encoder.encodeString.contramap[_root_.java.util.UUID](uuid => uuid.toString) private[v1] implicit val decodeInstant: Decoder[_root_.java.time.Instant] = Decoder.decodeString.emapTry(str => Try(_root_.java.time.OffsetDateTime.parse(str).toInstant)) private[v1] implicit val encodeInstant: Encoder[_root_.java.time.Instant] = Encoder.encodeString.contramap[_root_.java.time.Instant](_.toString) private[v1] implicit val decodeLocalDate: Decoder[_root_.java.time.LocalDate] = Decoder.decodeString.emapTry(str => Try(_root_.java.time.LocalDate.parse(str))) private[v1] implicit val encodeLocalDate: Encoder[_root_.java.time.LocalDate] = Encoder.encodeString.contramap[_root_.java.time.LocalDate](_.toString) implicit def decodeCatalystSquadHelloWorldExampleApiHello: Decoder[Hello] = Decoder.instance { c => for { id <- c.downField("id").as[_root_.java.util.UUID] name <- c.downField("name").as[String] } yield { Hello( id = id, name = name ) } } implicit def encodeCatalystSquadHelloWorldExampleApiHello: Encoder[Hello] = Encoder.instance { t => Json.fromFields(Seq( Some("id" -> t.id.asJson), Some("name" -> t.name.asJson) ).flatten) } implicit def decodeCatalystSquadHelloWorldExampleApiNewhello: Decoder[Newhello] = Decoder.instance { c => for { name <- c.downField("name").as[String] } yield { Newhello( name = name ) } } implicit def encodeCatalystSquadHelloWorldExampleApiNewhello: Encoder[Newhello] = Encoder.instance { t => Json.fromFields(Seq( Some("name" -> t.name.asJson) ).flatten) } } } package com.catalystsquad.catalyst.squad.hello.world.example.api.v1 { import cats.effect._ import cats.implicits._ import io.circe.syntax._ object Constants { val Namespace = "com.catalystsquad.catalyst.squad.hello.world.example.api.v1" val UserAgent = "apibuilder app.apibuilder.io/catalystsquad/catalyst-squad-hello-world-example-api/1.0.1/http4s_0_20" val Version = "1.0.1" val VersionMajor = 1 } class Client[F[_]: Sync]( val baseUrl: org.http4s.Uri, auth: scala.Option[com.catalystsquad.catalyst.squad.hello.world.example.api.v1.Authorization] = None, defaultHeaders: Seq[(String, String)] = Nil, httpClient: org.http4s.client.Client[F] ) extends interfaces.Client[F] { import org.http4s.Response import com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.json._ def helloes: Helloes[F] = Helloes object Helloes extends Helloes[F] { override def get( requestHeaders: Seq[(String, String)] = Nil ): F[com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.Hello] = { val urlPath = Seq("helloes") _executeRequest[Unit, com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.Hello]("GET", path = urlPath, requestHeaders = requestHeaders) { case r if r.status.code == 200 => _root_.com.catalystsquad.catalyst.squad.hello.world.example.api.v1.Client.parseJson[F, com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.Hello]("com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.Hello", r) case r if r.status.code == 404 => Sync[F].raiseError(new com.catalystsquad.catalyst.squad.hello.world.example.api.v1.errors.UnitResponse(r.status.code)) case r => Sync[F].raiseError(new com.catalystsquad.catalyst.squad.hello.world.example.api.v1.errors.FailedRequest(r.status.code, s"Unsupported response code[${r.status.code}]. Expected: 200, 404")) } } override def post( requestHeaders: Seq[(String, String)] = Nil ): F[com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.Hello] = { val urlPath = Seq("helloes") _executeRequest[Unit, com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.Hello]("POST", path = urlPath, requestHeaders = requestHeaders) { case r if r.status.code == 200 => _root_.com.catalystsquad.catalyst.squad.hello.world.example.api.v1.Client.parseJson[F, com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.Hello]("com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.Hello", r) case r if r.status.code == 401 => _root_.com.catalystsquad.catalyst.squad.hello.world.example.api.v1.Client.parseJson[F, String]("String", r).flatMap(body => Sync[F].raiseError(new com.catalystsquad.catalyst.squad.hello.world.example.api.v1.errors.ValueResponse(r.headers, r.status.code, None, body))) case r => Sync[F].raiseError(new com.catalystsquad.catalyst.squad.hello.world.example.api.v1.errors.FailedRequest(r.status.code, s"Unsupported response code[${r.status.code}]. Expected: 200, 401")) } } } private lazy val defaultApiHeaders = Seq( ("User-Agent", Constants.UserAgent), ("X-Apidoc-Version", Constants.Version), ("X-Apidoc-Version-Major", Constants.VersionMajor.toString) ) def apiHeaders: Seq[(String, String)] = defaultApiHeaders def modifyRequest(request: org.http4s.Request[F]): org.http4s.Request[F] = request implicit def circeJsonEncoder[F[_]: Sync, A](implicit encoder: io.circe.Encoder[A]) = org.http4s.circe.jsonEncoderOf[F, A] def _executeRequest[T, U]( method: String, path: Seq[String], queryParameters: Seq[(String, String)] = Nil, requestHeaders: Seq[(String, String)] = Nil, body: Option[T] = None, formBody : Option[org.http4s.UrlForm] = None )(handler: org.http4s.Response[F] => F[U] )(implicit encoder: io.circe.Encoder[T]): F[U] = { import org.http4s.QueryParamEncoder._ val m = org.http4s.Method.fromString(method) match { case Right(m) => m case Left(e) => sys.error(e.toString) } val headers = org.http4s.Headers(( apiHeaders ++ defaultHeaders ++ requestHeaders ).groupBy(_._1).map { case (k, l) => org.http4s.Header(k, l.last._2) }.toList) val queryMap = queryParameters.groupBy(_._1).map { case (k, v) => k -> v.map(_._2) } val uri = path.foldLeft(baseUrl){ case (uri, segment) => uri / segment }.setQueryParams(queryMap) val request = org.http4s.Request[F](method = m, uri = uri, headers = headers) val reqAndMaybeAuth = auth.fold(request) { case Authorization.Basic(username, passwordOpt) => { val userpass = s"$username:${passwordOpt.getOrElse("")}" val token = java.util.Base64.getEncoder.encodeToString(userpass.getBytes(java.nio.charset.StandardCharsets.ISO_8859_1)) request.putHeaders(org.http4s.Header("Authorization", s"Basic $token")) } case a => sys.error("Invalid authorization scheme[" + a.getClass + "]") } val reqAndMaybeAuthAndBody = if (formBody.nonEmpty) formBody.fold(reqAndMaybeAuth)(reqAndMaybeAuth.withEntity) else body.fold(reqAndMaybeAuth)(reqAndMaybeAuth.withEntity) httpClient.fetch(modifyRequest(reqAndMaybeAuthAndBody))(handler) } } object Client { import cats.effect._ implicit def circeJsonDecoder[F[_]: Sync, A](implicit decoder: io.circe.Decoder[A]) = org.http4s.circe.jsonOf[F, A] def parseJson[F[_]: Sync, T]( className: String, r: org.http4s.Response[F] )(implicit decoder: io.circe.Decoder[T]): F[T] = r.attemptAs[T].value.flatMap { case Right(value) => Sync[F].pure(value) case Left(error) => Sync[F].raiseError(new com.catalystsquad.catalyst.squad.hello.world.example.api.v1.errors.FailedRequest(r.status.code, s"Invalid json for class[" + className + "]", None, error)) } } sealed trait Authorization extends _root_.scala.Product with _root_.scala.Serializable object Authorization { final case class Basic(username: String, password: Option[String] = None) extends Authorization } package interfaces { trait Client[F[_]] { def baseUrl: org.http4s.Uri def helloes: com.catalystsquad.catalyst.squad.hello.world.example.api.v1.Helloes[F] } } trait Helloes[F[_]] { def get( requestHeaders: Seq[(String, String)] = Nil ): F[com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.Hello] def post( requestHeaders: Seq[(String, String)] = Nil ): F[com.catalystsquad.catalyst.squad.hello.world.example.api.v1.models.Hello] } package errors { final case class UnitResponse(status: Int) extends Exception(s"HTTP $status") final case class ValueResponse( headers: org.http4s.Headers, status: Int, message: Option[String] = None, body: String ) extends Exception(s"HTTP $status${message.fold("")(m => s": $m")}"){ lazy val value = body } final case class FailedRequest(responseCode: Int, message: String, requestUri: Option[_root_.java.net.URI] = None, parent: Exception = null) extends _root_.java.lang.Exception(s"HTTP $responseCode: $message", parent) } }