/** * Generated by API Builder - https://www.apibuilder.io * Service version: 1.1.0 * User agent: apibuilder app.apibuilder.io/hbc/api-product-recommendations-lat/1.1.0/http4s_0_22 */ package com.hbc.api.product.recommendations.lat.v1.models { /** * Product price in USD * * @param was formatted price in USD * @param now formatted price in USD * @param onSale true if now price is < was price. Used to */ final case class Price( was: String, now: String, onSale: Boolean = false ) /** * @param rating customer review's rating * @param numReviews number of customers that reviewed the product */ final case class Recommendation( productId: String, productName: String, productUrl: String, productImageUrl: String, brandName: String, price: com.hbc.api.product.recommendations.lat.v1.models.Price, rating: _root_.scala.Option[Double] = None, numReviews: _root_.scala.Option[Long] = None ) final case class SimilarProductRecommendation( recommendations: Seq[com.hbc.api.product.recommendations.lat.v1.models.Recommendation] ) sealed trait SimilarProductContext extends _root_.scala.Product with _root_.scala.Serializable object SimilarProductContext { /** * PDP page. (Strict category match) */ case object Pdp extends SimilarProductContext { override def toString = "pdp" } /** * 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 SimilarProductContext /** * 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[SimilarProductContext] = scala.List(Pdp) private val byName: Map[String, SimilarProductContext] = all.map(x => x.toString.toLowerCase -> x).toMap def apply(value: String): SimilarProductContext = fromString(value).getOrElse(UNDEFINED(value)) def fromString(value: String): _root_.scala.Option[SimilarProductContext] = byName.get(value.toLowerCase) } } package com.hbc.api.product.recommendations.lat.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.hbc.api.product.recommendations.lat.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 val jsonDecoderApiProductRecommendationsLatSimilarProductContext: Decoder[com.hbc.api.product.recommendations.lat.v1.models.SimilarProductContext] = Decoder.decodeString.map(com.hbc.api.product.recommendations.lat.v1.models.SimilarProductContext(_)) implicit val jsonEncoderApiProductRecommendationsLatSimilarProductContext: Encoder[com.hbc.api.product.recommendations.lat.v1.models.SimilarProductContext] = Encoder.encodeString.contramap[com.hbc.api.product.recommendations.lat.v1.models.SimilarProductContext](_.toString) implicit def decodeApiProductRecommendationsLatPrice: Decoder[Price] = Decoder.instance { c => for { was <- c.downField("was").as[String] now <- c.downField("now").as[String] onSale <- c.downField("onSale").as[Boolean] } yield { Price( was = was, now = now, onSale = onSale ) } } implicit def encodeApiProductRecommendationsLatPrice: Encoder[Price] = Encoder.instance { t => Json.fromFields(Seq( Some("was" -> t.was.asJson), Some("now" -> t.now.asJson), Some("onSale" -> t.onSale.asJson) ).flatten) } implicit def decodeApiProductRecommendationsLatRecommendation: Decoder[Recommendation] = Decoder.instance { c => for { productId <- c.downField("productId").as[String] productName <- c.downField("productName").as[String] productUrl <- c.downField("productUrl").as[String] productImageUrl <- c.downField("productImageUrl").as[String] brandName <- c.downField("brandName").as[String] price <- c.downField("price").as[com.hbc.api.product.recommendations.lat.v1.models.Price] rating <- c.downField("rating").as[Option[Double]] numReviews <- c.downField("numReviews").as[Option[Long]] } yield { Recommendation( productId = productId, productName = productName, productUrl = productUrl, productImageUrl = productImageUrl, brandName = brandName, price = price, rating = rating, numReviews = numReviews ) } } implicit def encodeApiProductRecommendationsLatRecommendation: Encoder[Recommendation] = Encoder.instance { t => Json.fromFields(Seq( Some("productId" -> t.productId.asJson), Some("productName" -> t.productName.asJson), Some("productUrl" -> t.productUrl.asJson), Some("productImageUrl" -> t.productImageUrl.asJson), Some("brandName" -> t.brandName.asJson), Some("price" -> t.price.asJson), t.rating.map(t => "rating" -> t.asJson), t.numReviews.map(t => "numReviews" -> t.asJson) ).flatten) } implicit def decodeApiProductRecommendationsLatSimilarProductRecommendation: Decoder[SimilarProductRecommendation] = Decoder.instance { c => for { recommendations <- c.downField("recommendations").as[Seq[com.hbc.api.product.recommendations.lat.v1.models.Recommendation]] } yield { SimilarProductRecommendation( recommendations = recommendations ) } } implicit def encodeApiProductRecommendationsLatSimilarProductRecommendation: Encoder[SimilarProductRecommendation] = Encoder.instance { t => Json.fromFields(Seq( Some("recommendations" -> t.recommendations.asJson) ).flatten) } } } package com.hbc.api.product.recommendations.lat.v1 { import cats.effect._ import cats.implicits._ import io.circe.syntax._ object Constants { val BaseUrl = "https://m.lordandtaylor.com/api-product-suggestions" val Namespace = "com.hbc.api.product.recommendations.lat.v1" val UserAgent = "apibuilder app.apibuilder.io/hbc/api-product-recommendations-lat/1.1.0/http4s_0_22" val Version = "1.1.0" val VersionMajor = 1 } class Client[F[_]: Sync]( val baseUrl: org.http4s.Uri = org.http4s.Uri.unsafeFromString("https://m.lordandtaylor.com/api-product-suggestions"), auth: scala.Option[com.hbc.api.product.recommendations.lat.v1.Authorization] = None, defaultHeaders: Seq[(String, String)] = Nil, httpClient: org.http4s.client.Client[F] ) extends interfaces.Client[F] { import org.http4s.Response import com.hbc.api.product.recommendations.lat.v1.models.json._ def similarProductRecommendations: SimilarProductRecommendations[F] = SimilarProductRecommendations object SimilarProductRecommendations extends SimilarProductRecommendations[F] { override def getByContextAndProductId( context: com.hbc.api.product.recommendations.lat.v1.models.SimilarProductContext = com.hbc.api.product.recommendations.lat.v1.models.SimilarProductContext.Pdp, productId: String, color: _root_.scala.Option[String] = None, limit: Int = 10, abTestName: _root_.scala.Option[String] = None, abTestVariant: _root_.scala.Option[String] = None, referer: String, requestHeaders: Seq[(String, String)] = Nil ): F[com.hbc.api.product.recommendations.lat.v1.models.SimilarProductRecommendation] = { val urlPath = Seq("similarProductRecommendations", context.toString, productId) val queryParameters = Seq( color.map("color" -> _), Some("limit" -> limit.toString), abTestName.map("abTestName" -> _), abTestVariant.map("abTestVariant" -> _) ).flatten val headerParameters = Seq( Some("Referer" -> referer) ).flatten _executeRequest[Unit, com.hbc.api.product.recommendations.lat.v1.models.SimilarProductRecommendation]("GET", path = urlPath, queryParameters = queryParameters, requestHeaders = (requestHeaders ++ headerParameters)) { case r if r.status.code == 200 => _root_.com.hbc.api.product.recommendations.lat.v1.Client.parseJson[F, com.hbc.api.product.recommendations.lat.v1.models.SimilarProductRecommendation]("com.hbc.api.product.recommendations.lat.v1.models.SimilarProductRecommendation", r) case r => Sync[F].raiseError(new com.hbc.api.product.recommendations.lat.v1.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 com.hbc.api.product.recommendations.lat.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 similarProductRecommendations: com.hbc.api.product.recommendations.lat.v1.SimilarProductRecommendations[F] } } trait SimilarProductRecommendations[F[_]] { /** * Gets similar products recommendations inferring the org from the domain referrer * * @param context Context in which to show similar products, eg: PDP * @param productId Product code for which we want to return similar products * @param color plain text color * @param limit Limit on number of recommendations to be returned * @param referer The service will use the content of this header to infer the org * @param abTestName Name of the abTest being run (if any) * @param abTestVariant Variant in the abTest (if any) */ def getByContextAndProductId( context: com.hbc.api.product.recommendations.lat.v1.models.SimilarProductContext = com.hbc.api.product.recommendations.lat.v1.models.SimilarProductContext.Pdp, productId: String, color: _root_.scala.Option[String] = None, limit: Int = 10, abTestName: _root_.scala.Option[String] = None, abTestVariant: _root_.scala.Option[String] = None, referer: String, requestHeaders: Seq[(String, String)] = Nil ): F[com.hbc.api.product.recommendations.lat.v1.models.SimilarProductRecommendation] } package errors { 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) } }