/** * Generated by API Builder - https://www.apibuilder.io * Service version: 0.0.1-dev * User agent: apibuilder app.apibuilder.io/poole-solutions/questlog-api/0.0.1-dev/http4s_0_22 */ package solutions.poole.questlog.api.v0.models { /** * @param guid primary key */ trait DatabaseRecord { def guid: _root_.java.util.UUID } sealed trait Person extends _root_.scala.Product with _root_.scala.Serializable { def personDiscriminator: PersonDiscriminator def email: _root_.scala.Option[String] def name: _root_.scala.Option[String] } /** * Defines the valid discriminator values for the type Person */ sealed trait PersonDiscriminator extends _root_.scala.Product with _root_.scala.Serializable object PersonDiscriminator { case object Guest extends PersonDiscriminator { override def toString = "guest" } case object User extends PersonDiscriminator { override def toString = "user" } final case class UNDEFINED(override val toString: String) extends PersonDiscriminator val all: scala.List[PersonDiscriminator] = scala.List(Guest, User) private val byName: Map[String, PersonDiscriminator] = all.map(x => x.toString.toLowerCase -> x).toMap def apply(value: String): PersonDiscriminator = fromString(value).getOrElse(UNDEFINED(value)) def fromString(value: String): _root_.scala.Option[PersonDiscriminator] = byName.get(value.toLowerCase) } /** * Represents an adventure. */ final case class Adventure( override val guid: _root_.java.util.UUID, name: String, description: _root_.scala.Option[String] = None, location: _root_.scala.Option[String] = None, participants: _root_.scala.Option[Seq[solutions.poole.questlog.api.v0.models.Participant]] = None, packLists: _root_.scala.Option[Seq[solutions.poole.questlog.api.v0.models.Item]] = None ) extends DatabaseRecord /** * Represents a validation error from the application. */ final case class Error( code: String, message: String ) final case class Guest( override val email: _root_.scala.Option[String] = None, override val name: _root_.scala.Option[String] = None ) extends Person { override val personDiscriminator: PersonDiscriminator = PersonDiscriminator.Guest } final case class Item( name: String, size: _root_.scala.Option[Double] = None, description: _root_.scala.Option[String] = None, `type`: _root_.scala.Option[solutions.poole.questlog.api.v0.models.ItemType] = None ) /** * Represents a adventure participant and what items they will bring. */ final case class Participant( person: solutions.poole.questlog.api.v0.models.Person, items: _root_.scala.Option[Seq[solutions.poole.questlog.api.v0.models.Item]] = None ) final case class User( override val guid: _root_.java.util.UUID, override val email: _root_.scala.Option[String] = None, override val name: _root_.scala.Option[String] = None ) extends DatabaseRecord with Person { override val personDiscriminator: PersonDiscriminator = PersonDiscriminator.User } /** * Provides future compatibility in clients - in the future, when a type is added * to the union Person, it will need to be handled in the client code. This * implementation will deserialize these future types as an instance of this class. * * @param description Information about the type that we received that is undefined in this version of * the client. */ final case class PersonUndefinedType( description: String ) extends Person { override val personDiscriminator: PersonDiscriminator = PersonDiscriminator.UNDEFINED(description) override def email: _root_.scala.Option[String] = ??? override def name: _root_.scala.Option[String] = ??? } sealed trait ItemType extends _root_.scala.Product with _root_.scala.Serializable object ItemType { /** * Required to keep going */ case object Food extends ItemType { override def toString = "Food" } /** * Required to fend of nature */ case object Clothes extends ItemType { override def toString = "Clothes" } /** * Required for sleep */ case object Camp extends ItemType { override def toString = "Camp" } /** * Required for eating */ case object Utensils extends ItemType { override def toString = "Utensils" } /** * Required to perform the given activity */ case object Gear extends ItemType { override def toString = "Gear" } /** * UNDEFINED captures values that are sent either in error or * that were added by the server after this library was * generated. We want to make it easy and obvious to users of * this library to handle this case gracefully. * * We use all CAPS for the variable name to avoid collisions * with the camel cased values above. */ final case class UNDEFINED(override val toString: String) extends ItemType /** * all returns a list of all the valid, known values. We use * lower case to avoid collisions with the camel cased values * above. */ val all: scala.List[ItemType] = scala.List(Food, Clothes, Camp, Utensils, Gear) private val byName: Map[String, ItemType] = all.map(x => x.toString.toLowerCase -> x).toMap def apply(value: String): ItemType = fromString(value).getOrElse(UNDEFINED(value)) def fromString(value: String): _root_.scala.Option[ItemType] = byName.get(value.toLowerCase) } } package solutions.poole.questlog.api.v0.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 solutions.poole.questlog.api.v0.models.json._ // Make Scala 2.11 Either monadic private[v0] implicit def eitherOps[A,B](e: Either[A,B]) = cats.implicits.catsSyntaxEither(e) private[v0] implicit val decodeUUID: Decoder[_root_.java.util.UUID] = Decoder.decodeString.emapTry(str => Try(_root_.java.util.UUID.fromString(str))) private[v0] implicit val encodeUUID: Encoder[_root_.java.util.UUID] = Encoder.encodeString.contramap[_root_.java.util.UUID](uuid => uuid.toString) private[v0] implicit val decodeInstant: Decoder[_root_.java.time.Instant] = Decoder.decodeString.emapTry(str => Try(_root_.java.time.OffsetDateTime.parse(str).toInstant)) private[v0] implicit val encodeInstant: Encoder[_root_.java.time.Instant] = Encoder.encodeString.contramap[_root_.java.time.Instant](_.toString) private[v0] implicit val decodeLocalDate: Decoder[_root_.java.time.LocalDate] = Decoder.decodeString.emapTry(str => Try(_root_.java.time.LocalDate.parse(str))) private[v0] implicit val encodeLocalDate: Encoder[_root_.java.time.LocalDate] = Encoder.encodeString.contramap[_root_.java.time.LocalDate](_.toString) implicit val jsonDecoderQuestlogApiItemType: Decoder[solutions.poole.questlog.api.v0.models.ItemType] = Decoder.decodeString.map(solutions.poole.questlog.api.v0.models.ItemType(_)) implicit val jsonEncoderQuestlogApiItemType: Encoder[solutions.poole.questlog.api.v0.models.ItemType] = Encoder.encodeString.contramap[solutions.poole.questlog.api.v0.models.ItemType](_.toString) implicit def decodeQuestlogApiAdventure: Decoder[Adventure] = Decoder.instance { c => for { guid <- c.downField("guid").as[_root_.java.util.UUID] name <- c.downField("name").as[String] description <- c.downField("description").as[Option[String]] location <- c.downField("location").as[Option[String]] participants <- c.downField("participants").as[Option[Seq[solutions.poole.questlog.api.v0.models.Participant]]] packLists <- c.downField("pack_lists").as[Option[Seq[solutions.poole.questlog.api.v0.models.Item]]] } yield { Adventure( guid = guid, name = name, description = description, location = location, participants = participants, packLists = packLists ) } } implicit def encodeQuestlogApiAdventure: Encoder[Adventure] = Encoder.instance { t => Json.fromFields(Seq( Some("guid" -> t.guid.asJson), Some("name" -> t.name.asJson), t.description.map(t => "description" -> t.asJson), t.location.map(t => "location" -> t.asJson), t.participants.map(t => "participants" -> t.asJson), t.packLists.map(t => "pack_lists" -> t.asJson) ).flatten) } implicit def decodeQuestlogApiError: Decoder[Error] = Decoder.instance { c => for { code <- c.downField("code").as[String] message <- c.downField("message").as[String] } yield { Error( code = code, message = message ) } } implicit def encodeQuestlogApiError: Encoder[Error] = Encoder.instance { t => Json.fromFields(Seq( Some("code" -> t.code.asJson), Some("message" -> t.message.asJson) ).flatten) } implicit def decodeQuestlogApiGuest: Decoder[Guest] = Decoder.instance { c => for { email <- c.downField("email").as[Option[String]] name <- c.downField("name").as[Option[String]] } yield { Guest( email = email, name = name ) } } implicit def encodeQuestlogApiGuest: Encoder[Guest] = Encoder.instance { t => Json.fromFields(Seq( t.email.map(t => "email" -> t.asJson), t.name.map(t => "name" -> t.asJson) ).flatten) } implicit def decodeQuestlogApiItem: Decoder[Item] = Decoder.instance { c => for { name <- c.downField("name").as[String] size <- c.downField("size").as[Option[Double]] description <- c.downField("description").as[Option[String]] __type__ <- c.downField("type").as[Option[solutions.poole.questlog.api.v0.models.ItemType]] } yield { Item( name = name, size = size, description = description, `type` = __type__ ) } } implicit def encodeQuestlogApiItem: Encoder[Item] = Encoder.instance { t => Json.fromFields(Seq( Some("name" -> t.name.asJson), t.size.map(t => "size" -> t.asJson), t.description.map(t => "description" -> t.asJson), t.`type`.map(t => "type" -> t.asJson) ).flatten) } implicit def decodeQuestlogApiParticipant: Decoder[Participant] = Decoder.instance { c => for { person <- c.downField("person").as[solutions.poole.questlog.api.v0.models.Person] items <- c.downField("items").as[Option[Seq[solutions.poole.questlog.api.v0.models.Item]]] } yield { Participant( person = person, items = items ) } } implicit def encodeQuestlogApiParticipant: Encoder[Participant] = Encoder.instance { t => Json.fromFields(Seq( Some("person" -> t.person.asJson), t.items.map(t => "items" -> t.asJson) ).flatten) } implicit def decodeQuestlogApiUser: Decoder[User] = Decoder.instance { c => for { guid <- c.downField("guid").as[_root_.java.util.UUID] email <- c.downField("email").as[Option[String]] name <- c.downField("name").as[Option[String]] } yield { User( guid = guid, email = email, name = name ) } } implicit def encodeQuestlogApiUser: Encoder[User] = Encoder.instance { t => Json.fromFields(Seq( Some("guid" -> t.guid.asJson), t.email.map(t => "email" -> t.asJson), t.name.map(t => "name" -> t.asJson) ).flatten) } implicit def decodeQuestlogApiPerson: Decoder[Person] = Decoder.instance { c => c.get[Option[String]]("discriminator") match { case Right(Some(s)) if s == "guest" => c.as[solutions.poole.questlog.api.v0.models.Guest] case Right(Some(s)) if s == "user" => c.as[solutions.poole.questlog.api.v0.models.User] case Right(Some(s)) => Right(solutions.poole.questlog.api.v0.models.PersonUndefinedType(s)) case _ => Left(DecodingFailure("Union[Person] requires a discriminator named 'discriminator' - this field was not found in the Json", c.history)) } } implicit def encodeQuestlogApiPerson: Encoder[Person] = Encoder.instance { case t: solutions.poole.questlog.api.v0.models.Guest => t.asJson.mapObject(obj => ("discriminator", Json.fromString("guest")) +: obj) case t: solutions.poole.questlog.api.v0.models.User => t.asJson.mapObject(obj => ("discriminator", Json.fromString("user")) +: obj) case other => sys.error(s"The type[${other.getClass.getName}] has no JSON encoder") } } } package solutions.poole.questlog.api.v0 { import cats.effect._ import cats.implicits._ import io.circe.syntax._ object Constants { val BaseUrl = "https://api.questlog.io" val Namespace = "solutions.poole.questlog.api.v0" val UserAgent = "apibuilder app.apibuilder.io/poole-solutions/questlog-api/0.0.1-dev/http4s_0_22" val Version = "0.0.1-dev" val VersionMajor = 0 } class Client[F[_]: Sync]( val baseUrl: org.http4s.Uri = org.http4s.Uri.unsafeFromString("https://api.questlog.io"), auth: scala.Option[solutions.poole.questlog.api.v0.Authorization] = None, defaultHeaders: Seq[(String, String)] = Nil, httpClient: org.http4s.client.Client[F] ) extends interfaces.Client[F] { import org.http4s.Response import solutions.poole.questlog.api.v0.models.json._ def adventures: Adventures[F] = Adventures object Adventures extends Adventures[F] { override def post( adventure: solutions.poole.questlog.api.v0.models.Adventure, requestHeaders: Seq[(String, String)] = Nil ): F[solutions.poole.questlog.api.v0.models.Adventure] = { val urlPath = Seq("adventures") val payload = None val formPayload = Some(org.http4s.UrlForm( "adventure" -> adventure.asJson.noSpaces )) _executeRequest[Unit, solutions.poole.questlog.api.v0.models.Adventure]("POST", path = urlPath, body = payload, formBody = formPayload, requestHeaders = requestHeaders) { case r if r.status.code == 201 => _root_.solutions.poole.questlog.api.v0.Client.parseJson[F, solutions.poole.questlog.api.v0.models.Adventure]("solutions.poole.questlog.api.v0.models.Adventure", r) case r if r.status.code == 409 => _root_.solutions.poole.questlog.api.v0.Client.parseJson[F, Seq[solutions.poole.questlog.api.v0.models.Error]]("Seq[solutions.poole.questlog.api.v0.models.Error]", r).flatMap(body => Sync[F].raiseError(new solutions.poole.questlog.api.v0.errors.ErrorsResponse(r.headers, r.status.code, None, body))) case r => Sync[F].raiseError(new solutions.poole.questlog.api.v0.errors.FailedRequest(r.status.code, s"Unsupported response code[${r.status.code}]. Expected: 201, 409")) } } override def get( guid: _root_.scala.Option[_root_.java.util.UUID] = None, name: _root_.scala.Option[String] = None, requestHeaders: Seq[(String, String)] = Nil ): F[Seq[solutions.poole.questlog.api.v0.models.Adventure]] = { val urlPath = Seq("adventures") val queryParameters = Seq( guid.map("guid" -> _.toString), name.map("name" -> _) ).flatten _executeRequest[Unit, Seq[solutions.poole.questlog.api.v0.models.Adventure]]("GET", path = urlPath, queryParameters = queryParameters, requestHeaders = requestHeaders) { case r if r.status.code == 200 => _root_.solutions.poole.questlog.api.v0.Client.parseJson[F, Seq[solutions.poole.questlog.api.v0.models.Adventure]]("Seq[solutions.poole.questlog.api.v0.models.Adventure]", r) case r => Sync[F].raiseError(new solutions.poole.questlog.api.v0.errors.FailedRequest(r.status.code, s"Unsupported response code[${r.status.code}]. Expected: 200")) } } override def getByGuid( guid: _root_.java.util.UUID, requestHeaders: Seq[(String, String)] = Nil ): F[solutions.poole.questlog.api.v0.models.Adventure] = { val urlPath = Seq("adventures", guid.toString) _executeRequest[Unit, solutions.poole.questlog.api.v0.models.Adventure]("GET", path = urlPath, requestHeaders = requestHeaders) { case r if r.status.code == 200 => _root_.solutions.poole.questlog.api.v0.Client.parseJson[F, solutions.poole.questlog.api.v0.models.Adventure]("solutions.poole.questlog.api.v0.models.Adventure", r) case r => Sync[F].raiseError(new solutions.poole.questlog.api.v0.errors.FailedRequest(r.status.code, s"Unsupported response code[${r.status.code}]. Expected: 200")) } } } 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.Raw(org.typelevel.ci.CIString(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.Raw(org.typelevel.ci.CIString("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 solutions.poole.questlog.api.v0.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 adventures: solutions.poole.questlog.api.v0.Adventures[F] } } trait Adventures[F[_]] { def post( adventure: solutions.poole.questlog.api.v0.models.Adventure, requestHeaders: Seq[(String, String)] = Nil ): F[solutions.poole.questlog.api.v0.models.Adventure] def get( guid: _root_.scala.Option[_root_.java.util.UUID] = None, name: _root_.scala.Option[String] = None, requestHeaders: Seq[(String, String)] = Nil ): F[Seq[solutions.poole.questlog.api.v0.models.Adventure]] def getByGuid( guid: _root_.java.util.UUID, requestHeaders: Seq[(String, String)] = Nil ): F[solutions.poole.questlog.api.v0.models.Adventure] } package errors { final case class ErrorsResponse( headers: org.http4s.Headers, status: Int, message: Option[String] = None, body: Seq[solutions.poole.questlog.api.v0.models.Error] ) extends Exception(s"HTTP $status${message.fold("")(m => s": $m")}"){ lazy val errors = 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) } }