akka.http.scaladsl.marshalling.ToResponseMarshaller Scala Examples
The following examples show how to use akka.http.scaladsl.marshalling.ToResponseMarshaller.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: AuthRoute.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.api.routes import akka.http.scaladsl.marshalling.{ToResponseMarshallable, ToResponseMarshaller} import akka.http.scaladsl.model.{StatusCode, StatusCodes} import akka.http.scaladsl.server.{Directive0, Directive1} import com.wavesplatform.dex.api.http.entities.{MatcherResponse, SimpleErrorResponse} import com.wavesplatform.dex.api.http.headers.{`X-Api-Key`, `X-User-Public-Key`, api_key} import com.wavesplatform.dex.api.ws.routes.MatcherWebSocketRoute import com.wavesplatform.dex.domain.account.PublicKey import com.wavesplatform.dex.domain.crypto import com.wavesplatform.dex.error.{ApiKeyIsNotProvided, ApiKeyIsNotValid, MatcherError, UserPublicKeyIsNotValid} trait AuthRoute { this: ApiRoute => protected val apiKeyHash: Option[Array[Byte]] def withAuth(implicit matcherResponseTrm: ToResponseMarshaller[MatcherResponse]): Directive0 = { def correctResponse(statusCode: StatusCode, matcherError: MatcherError): ToResponseMarshallable = this match { case _: MatcherWebSocketRoute => matcherError.toWsHttpResponse(statusCode) case _ => SimpleErrorResponse(statusCode, matcherError) } apiKeyHash.fold[Directive0] { complete(SimpleErrorResponse(StatusCodes.InternalServerError, ApiKeyIsNotProvided)) } { hashFromSettings => optionalHeaderValueByType[`X-Api-Key`](()).flatMap { case Some(key) if java.util.Arrays.equals(crypto secureHash key.value, hashFromSettings) => pass case _ => optionalHeaderValueByType[api_key](()).flatMap { case Some(key) if java.util.Arrays.equals(crypto secureHash key.value, hashFromSettings) => pass case _ => complete { correctResponse(StatusCodes.Forbidden, ApiKeyIsNotValid) } } } } } def withUserPublicKeyOpt(implicit matcherResponseTrm: ToResponseMarshaller[MatcherResponse]): Directive1[Option[PublicKey]] = optionalHeaderValueByType[`X-User-Public-Key`](()).flatMap { case None => provide(None) case Some(rawPublicKey) => PublicKey.fromBase58String(rawPublicKey.value) match { case Left(_) => complete(SimpleErrorResponse(StatusCodes.BadRequest, UserPublicKeyIsNotValid)) case Right(x) => provide[Option[PublicKey]](Some(PublicKey(x))) } } }
Example 2
Source File: MatcherResponse.scala From matcher with MIT License | 5 votes |
package com.wavesplatform.dex.api.http.entities import akka.http.scaladsl.marshalling.{Marshaller, ToResponseMarshaller} import akka.http.scaladsl.model.{StatusCodes => C, _} import akka.util.ByteString import com.wavesplatform.dex.domain.bytes.ByteStr.byteStrFormat import com.wavesplatform.dex.domain.order.Order import com.wavesplatform.dex.error import com.wavesplatform.dex.error.MatcherError import com.wavesplatform.dex.meta.getSimpleName import play.api.libs.json._ sealed class MatcherResponse(val statusCode: StatusCode, val content: MatcherResponseContent) { def this(code: StatusCode, error: MatcherError) = this(code, MatcherResponseContent.Single(Json.toJsObject(error))) def this(code: StatusCode, error: JsObject) = this(code, MatcherResponseContent.Single(error)) def status: String = getSimpleName(this) } object MatcherResponse { val toResponseMarshaller: ToResponseMarshaller[MatcherResponse] = Marshaller.opaque(toHttpResponse) implicit val matcherResponseWrites: Writes[MatcherResponse] = Writes(toJson) def toHttpResponse(x: MatcherResponse): HttpResponse = HttpResponse( x.statusCode, entity = HttpEntity.Strict(ContentTypes.`application/json`, ByteString(Json.stringify(toJson(x)))) ) def toJson(x: MatcherResponse): JsValue = backwardCompatibleWrapper( x.status, x.statusCode, x.content match { case MatcherResponseContent.Single(r) => r case MatcherResponseContent.Multiple(xs) => Json.obj("message" -> Json.arr(xs.map(toJson))) } ) private def backwardCompatibleWrapper(status: String, code: StatusCode, json: JsObject): JsValue = { Json .obj( "success" -> ( code match { case _: C.Success => true case _ => false } ), "status" -> status ) .deepMerge( code match { case _: C.Success => JsObject.empty case _ => Json.obj("result" -> JsNull) // For a backward compatibility } ) .deepMerge(json) } } sealed trait MatcherResponseContent object MatcherResponseContent { case class Single(content: JsObject) extends MatcherResponseContent case class Multiple(content: List[MatcherResponse]) extends MatcherResponseContent } case class SimpleResponse(code: StatusCode, js: JsObject) extends MatcherResponse(code, MatcherResponseContent.Single(js)) object SimpleResponse { def apply(code: StatusCode, message: String): SimpleResponse = new SimpleResponse(code, Json.toJsObject(HttpMessage(message))) def apply[T](response: T, code: StatusCode = C.OK)(implicit writes: OWrites[T]): SimpleResponse = new SimpleResponse(code, writes.writes(response)) } case class OrderCanceled(orderId: Order.Id) extends MatcherResponse(C.OK, Json.obj("orderId" -> orderId)) case class OrderDeleted(orderId: Order.Id) extends MatcherResponse(C.OK, Json.obj("orderId" -> orderId)) case class SimpleErrorResponse(code: StatusCode, error: MatcherError) extends MatcherResponse(code, error) case class InvalidJsonResponse(error: MatcherError) extends MatcherResponse(C.BadRequest, error) case class OrderRejected(error: MatcherError) extends MatcherResponse(C.BadRequest, error) case class OrderCancelRejected(error: MatcherError) extends MatcherResponse(C.BadRequest, error) case object InvalidSignature extends MatcherResponse(C.BadRequest, error.RequestInvalidSignature) case class NotImplemented(error: MatcherError) extends MatcherResponse(C.NotImplemented, error) case class CanNotPersist(error: MatcherError) extends MatcherResponse(C.ServiceUnavailable, error) case class OrderBookUnavailable(error: MatcherError) extends MatcherResponse(C.ServiceUnavailable, error) case object DuringStart extends MatcherResponse(C.ServiceUnavailable, error.MatcherIsStarting) case object DuringShutdown extends MatcherResponse(C.ServiceUnavailable, error.MatcherIsStopping) case object TimedOut extends MatcherResponse(C.InternalServerError, error.RequestTimeout) case class InfoNotFound(error: MatcherError) extends MatcherResponse(C.NotFound, error) case class WavesNodeUnavailable(error: MatcherError) extends MatcherResponse(C.ServiceUnavailable, error) case class RateError(error: MatcherError, code: StatusCode = C.BadRequest) extends MatcherResponse(code, error) case object InternalError extends MatcherResponse(C.ServiceUnavailable, MatcherResponseContent.Single(Json.obj("message" -> "Internal server error"))) case class InvalidAddress(reason: String) extends MatcherResponse(C.BadRequest, error.InvalidAddress(reason))
Example 3
Source File: RestRoute.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.highlevelserver.route import akka.actor.ActorRef import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.marshalling.ToResponseMarshaller import akka.http.scaladsl.model.{ StatusCodes, Uri } import akka.http.scaladsl.server.{ Directives, Route } import akka.http.scaladsl.unmarshalling.FromRequestUnmarshaller import akka.pattern.ask import akka.util.Timeout import com.github.dnvriend.component.highlevelserver.dto.PersonWithId import com.github.dnvriend.component.highlevelserver.marshaller.Marshaller import com.github.dnvriend.component.simpleserver.dto.http.Person import scala.concurrent.Future // see: akka.http.scaladsl.marshalling.ToResponseMarshallable // see: akka.http.scaladsl.marshalling.PredefinedToResponseMarshallers object RestRoute extends Directives with SprayJsonSupport with Marshaller { def routes(personDb: ActorRef)(implicit timeout: Timeout, trmSingle: ToResponseMarshaller[PersonWithId], trmList: ToResponseMarshaller[List[PersonWithId]], fru: FromRequestUnmarshaller[Person]): Route = { pathEndOrSingleSlash { redirect(Uri("/api/person"), StatusCodes.PermanentRedirect) } ~ pathPrefix("api" / "person") { get { path(IntNumber) { id => println(s"PathEndsInNumber=$id") complete((personDb ? "findAll").mapTo[List[PersonWithId]]) } ~ pathEndOrSingleSlash { parameter("foo") { foo => println(s"foo=$foo") complete((personDb ? "findAll").mapTo[List[PersonWithId]]) } ~ parameter('bar) { bar => println(s"bar=$bar") complete((personDb ? "findAll").mapTo[List[PersonWithId]]) } ~ complete((personDb ? "findAll").mapTo[List[PersonWithId]]) } } ~ (post & pathEndOrSingleSlash & entity(as[Person])) { person => complete((personDb ? person).mapTo[PersonWithId]) } } ~ path("failure") { pathEnd { complete(Future.failed[String](new RuntimeException("Simulated Failure"))) } } ~ path("success") { pathEnd { complete(Future.successful("Success!!")) } } } }
Example 4
Source File: DisjunctionMarshaller.scala From akka-http-test with Apache License 2.0 | 5 votes |
package com.github.dnvriend.component.simpleserver.marshaller import akka.http.scaladsl.marshalling.{ Marshaller, ToResponseMarshaller } import akka.http.scaladsl.model.{ HttpEntity, _ } import com.github.dnvriend.component.simpleserver.marshaller.DisjunctionMarshaller.{ ErrorMessage, FatalError } import spray.json.JsonWriter import scalaz.Scalaz._ import scalaz._ object DisjunctionMarshaller { trait ErrorMessage { def description: String } trait FatalError extends ErrorMessage trait NonFatalError extends ErrorMessage } trait DisjunctionMarshaller { type DisjunctionNel[A, +B] = Disjunction[NonEmptyList[A], B] implicit def disjunctionMarshaller[A1, A2, B](implicit m1: Marshaller[A1, B], m2: Marshaller[A2, B]): Marshaller[Disjunction[A1, A2], B] = Marshaller { implicit ec => { case -\/(a1) => m1(a1) case \/-(a2) => m2(a2) } } implicit def errorDisjunctionMarshaller[A](implicit w1: JsonWriter[A], w2: JsonWriter[List[String]]): ToResponseMarshaller[DisjunctionNel[String, A]] = Marshaller.withFixedContentType(MediaTypes.`application/json`) { case -\/(errors) => HttpResponse( status = StatusCodes.BadRequest, entity = HttpEntity(ContentType(MediaTypes.`application/json`), w2.write(errors.toList).compactPrint) ) case \/-(success) => HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`), w1.write(success).compactPrint)) } implicit def errorMessageDisjunctionMarshaller[A <: ErrorMessage, B](implicit w1: JsonWriter[B], w2: JsonWriter[List[String]]): ToResponseMarshaller[DisjunctionNel[A, B]] = { def createResponseWithStatusCode(code: StatusCode, errors: List[ErrorMessage]) = HttpResponse( status = code, entity = HttpEntity(ContentType(MediaTypes.`application/json`), w2.write(errors.map(_.description)).compactPrint) ) Marshaller.withFixedContentType(MediaTypes.`application/json`) { case -\/(errors) if errors.toList.exists(_.isInstanceOf[FatalError]) => createResponseWithStatusCode(StatusCodes.InternalServerError, errors.toList) case -\/(errors) => createResponseWithStatusCode(StatusCodes.BadRequest, errors.toList) case \/-(success) => HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`), w1.write(success).compactPrint)) } } } trait ValidationMarshaller { implicit def validationMarshaller[A1, A2, B](implicit m1: Marshaller[A1, B], m2: Marshaller[A2, B]): Marshaller[Validation[A1, A2], B] = Marshaller { implicit ec => { case Failure(a1) => m1(a1) case Success(a2) => m2(a2) } } implicit def errorValidationMarshaller[A](implicit w1: JsonWriter[A], w2: JsonWriter[List[String]]): ToResponseMarshaller[ValidationNel[String, A]] = Marshaller.withFixedContentType(MediaTypes.`application/json`) { case Failure(errors) => HttpResponse( status = StatusCodes.BadRequest, entity = HttpEntity(ContentType(MediaTypes.`application/json`), w2.write(errors.toList).compactPrint) ) case Success(success) => HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`), w1.write(success).compactPrint)) } implicit def errorMessageValidationMarshaller[A <: ErrorMessage, B](implicit w1: JsonWriter[B], w2: JsonWriter[List[String]]): ToResponseMarshaller[ValidationNel[A, B]] = { def createResponseWithStatusCode(code: StatusCode, errors: List[ErrorMessage]) = HttpResponse( status = code, entity = HttpEntity(ContentType(MediaTypes.`application/json`), w2.write(errors.map(_.description)).compactPrint) ) Marshaller.withFixedContentType(MediaTypes.`application/json`) { case Failure(errors) if errors.toList.exists(_.isInstanceOf[FatalError]) => createResponseWithStatusCode(StatusCodes.InternalServerError, errors.toList) case Failure(errors) => createResponseWithStatusCode(StatusCodes.BadRequest, errors.toList) case Success(success) => HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`), w1.write(success).compactPrint)) } } }
Example 5
Source File: ExtraDirectives.scala From eclair with Apache License 2.0 | 5 votes |
package fr.acinq.eclair.api import akka.http.scaladsl.marshalling.ToResponseMarshaller import akka.http.scaladsl.model.StatusCodes.NotFound import akka.http.scaladsl.model.{ContentTypes, HttpResponse} import akka.http.scaladsl.server.{Directive1, Directives, MalformedFormFieldRejection, Route} import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.Crypto.PublicKey import fr.acinq.eclair.ApiTypes.ChannelIdentifier import fr.acinq.eclair.api.FormParamExtractors._ import fr.acinq.eclair.api.JsonSupport._ import fr.acinq.eclair.payment.PaymentRequest import fr.acinq.eclair.{MilliSatoshi, ShortChannelId} import scala.concurrent.Future import scala.util.{Failure, Success} trait ExtraDirectives extends Directives { // named and typed URL parameters used across several routes val shortChannelIdFormParam = "shortChannelId".as[ShortChannelId](shortChannelIdUnmarshaller) val shortChannelIdsFormParam = "shortChannelIds".as[List[ShortChannelId]](shortChannelIdsUnmarshaller) val channelIdFormParam = "channelId".as[ByteVector32](sha256HashUnmarshaller) val channelIdsFormParam = "channelIds".as[List[ByteVector32]](sha256HashesUnmarshaller) val nodeIdFormParam = "nodeId".as[PublicKey] val nodeIdsFormParam = "nodeIds".as[List[PublicKey]](pubkeyListUnmarshaller) val paymentHashFormParam = "paymentHash".as[ByteVector32](sha256HashUnmarshaller) val fromFormParam = "from".as[Long] val toFormParam = "to".as[Long] val amountMsatFormParam = "amountMsat".as[MilliSatoshi] val invoiceFormParam = "invoice".as[PaymentRequest] // custom directive to fail with HTTP 404 (and JSON response) if the element was not found def completeOrNotFound[T](fut: Future[Option[T]])(implicit marshaller: ToResponseMarshaller[T]): Route = onComplete(fut) { case Success(Some(t)) => complete(t) case Success(None) => complete(HttpResponse(NotFound).withEntity(ContentTypes.`application/json`, serialization.writePretty(ErrorResponse("Not found")))) case Failure(_) => reject } def withChannelIdentifier: Directive1[ChannelIdentifier] = formFields(channelIdFormParam.?, shortChannelIdFormParam.?).tflatMap { case (Some(channelId), None) => provide(Left(channelId)) case (None, Some(shortChannelId)) => provide(Right(shortChannelId)) case _ => reject(MalformedFormFieldRejection("channelId/shortChannelId", "Must specify either the channelId or shortChannelId (not both)")) } def withChannelsIdentifier: Directive1[List[ChannelIdentifier]] = formFields(channelIdFormParam.?, channelIdsFormParam.?, shortChannelIdFormParam.?, shortChannelIdsFormParam.?).tflatMap { case (None, None, None, None) => reject(MalformedFormFieldRejection("channelId(s)/shortChannelId(s)", "Must specify channelId, channelIds, shortChannelId or shortChannelIds")) case (channelId_opt, channelIds_opt, shortChannelId_opt, shortChannelIds_opt) => val channelId: List[ChannelIdentifier] = channelId_opt.map(cid => Left(cid)).toList val channelIds: List[ChannelIdentifier] = channelIds_opt.map(_.map(cid => Left(cid))).toList.flatten val shortChannelId: List[ChannelIdentifier] = shortChannelId_opt.map(scid => Right(scid)).toList val shortChannelIds: List[ChannelIdentifier] = shortChannelIds_opt.map(_.map(scid => Right(scid))).toList.flatten provide((channelId ++ channelIds ++ shortChannelId ++ shortChannelIds).distinct) } }
Example 6
Source File: ErrorDirectives.scala From nexus with Apache License 2.0 | 5 votes |
package ch.epfl.bluebrain.nexus.commons.http.directives import akka.http.scaladsl.marshalling.{Marshaller, ToResponseMarshaller} import akka.http.scaladsl.model._ import ch.epfl.bluebrain.nexus.commons.circe.ContextUri import ch.epfl.bluebrain.nexus.commons.circe.syntax._ import ch.epfl.bluebrain.nexus.commons.http.JsonLdCirceSupport.OrderedKeys import ch.epfl.bluebrain.nexus.commons.http.RdfMediaTypes import io.circe.{Encoder, Printer} implicit final def jsonLdMarshallerFromStatusAndEncoder[A](implicit statusFrom: StatusFrom[A], encoder: Encoder[A], context: ContextUri, orderedKeys: OrderedKeys = OrderedKeys(List("@context", "code", "message", "details", "")), printer: Printer = Printer.noSpaces.copy(dropNullValues = true) ): ToResponseMarshaller[A] = Marshaller.withFixedContentType(RdfMediaTypes.`application/ld+json`) { value => HttpResponse( status = statusFrom(value), entity = HttpEntity( RdfMediaTypes.`application/ld+json`, printer.print(encoder.mapJson(_.addContext(context)).apply(value).sortKeys) ) ) } }
Example 7
Source File: MyResource.scala From quiz-management-service with Apache License 2.0 | 5 votes |
package com.danielasfregola.quiz.management.routing import akka.http.scaladsl.marshalling.{ToResponseMarshaller, ToResponseMarshallable} import scala.concurrent.{ExecutionContext, Future} import akka.http.scaladsl.model.headers.Location import akka.http.scaladsl.server.{Directives, Route} import com.danielasfregola.quiz.management.serializers.JsonSupport trait MyResource extends Directives with JsonSupport { implicit def executionContext: ExecutionContext def completeWithLocationHeader[T](resourceId: Future[Option[T]], ifDefinedStatus: Int, ifEmptyStatus: Int): Route = onSuccess(resourceId) { case Some(t) => completeWithLocationHeader(ifDefinedStatus, t) case None => complete(ifEmptyStatus, None) } def completeWithLocationHeader[T](status: Int, resourceId: T): Route = extractRequestContext { requestContext => val request = requestContext.request val location = request.uri.copy(path = request.uri.path / resourceId.toString) respondWithHeader(Location(location)) { complete(status, None) } } def complete[T: ToResponseMarshaller](resource: Future[Option[T]]): Route = onSuccess(resource) { case Some(t) => complete(ToResponseMarshallable(t)) case None => complete(404, None) } def complete(resource: Future[Unit]): Route = onSuccess(resource) { complete(204, None) } }
Example 8
Source File: Routable.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.akkaHttp import akka.http.scaladsl.marshalling.ToResponseMarshaller import akka.http.scaladsl.server.Directives.complete import akka.http.scaladsl.server.Route import scala.annotation.implicitNotFound import scala.concurrent.Future @implicitNotFound("could not route ${Res} knowing that result should be ${Out}") trait Routable[Res, Out] { def route(res: => Res): Route } object Routable { implicit def single[A](implicit marshaller: ToResponseMarshaller[A]): Routable[A, A] = complete(_) implicit def future[A](implicit marshaller: ToResponseMarshaller[A]): Routable[Future[A], A] = complete(_) } @implicitNotFound("could not route ${Res} knowing that result should be ${Out}") trait RoutableIn[In, Res, Out] { def route(in: In, res: => Res): Route } object RoutableIn { implicit def byRoutable[Res, Out, In](implicit routable: Routable[Res, Out]): RoutableIn[In, Res, Out] = (_, res) => routable.route(res) }
Example 9
Source File: InnerSuite.scala From typed-schema with Apache License 2.0 | 5 votes |
package ru.tinkoff.tschema.akkaHttp import akka.http.scaladsl.marshalling.{Marshaller, Marshalling, ToResponseMarshaller} import akka.http.scaladsl.model.{ContentTypes, HttpResponse} import akka.http.scaladsl.testkit.ScalatestRouteTest import ru.tinkoff.tschema.syntax._ import org.scalatest.flatspec.AsyncFlatSpec import org.scalatest.matchers.should.Matchers import scala.language.reflectiveCalls class InnerSuite extends AsyncFlatSpec with ScalatestRouteTest with Matchers { object impl { object first { def get: String = "first" def post(message: String) = s"first $message" } val second = new { def get: String = "second" def post(message: String) = s"second $message" } } implicit val unitAsPlainText: ToResponseMarshaller[Unit] = Marshaller.strict(_ => Marshalling.WithFixedContentType(ContentTypes.NoContentType, () => HttpResponse())) def api = ( groupPrefix("first") |> (( opGet |> $$[String] ) <> ( opPost |> queryParam[String]("message") |> $$[String] )) ) <> ( groupPrefix("second") |> (( opGet |> $$[String] ) <> ( opPost |> body[String]("message") |> $$[String] )) ) val route = MkRoute(api)(impl) "first group" should "handle get" in Get("/first") ~> route ~> check { responseAs[String] shouldBe "first" } it should "handle post" in Post("/first?message=hello+oleg") ~> route ~> check { responseAs[String] shouldBe "first hello oleg" } "second group" should "handle get" in Get("/second") ~> route ~> check { responseAs[String] shouldBe "second" } it should "handle post" in Post("/second", "hello oleg") ~> route ~> check { responseAs[String] shouldBe "second hello oleg" } }
Example 10
Source File: JsonMarshallers.scala From scala-openrtb with Apache License 2.0 | 5 votes |
package com.powerspace.openrtb.akka.marshallers import akka.http.scaladsl.marshalling.{ToEntityMarshaller, ToResponseMarshaller} import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse, MediaTypes} import com.google.openrtb.{BidRequest, BidResponse} import io.circe.Encoder object JsonMarshallers { import akka.http.scaladsl.marshalling.Marshaller._ def bidRequestJsonMarshaller(implicit encoder: Encoder[BidRequest]): ToEntityMarshaller[BidRequest] = withFixedContentType(ContentTypes.`application/json`)( bidRequest => HttpEntity(MediaTypes.`application/json`, encoder.apply(bidRequest).toString) ) def bidResponseJsonMarshaller(implicit encoder: Encoder[BidResponse]): ToEntityMarshaller[BidResponse] = withFixedContentType(ContentTypes.`application/json`)( bidResponse => HttpEntity(MediaTypes.`application/json`, encoder.apply(bidResponse).toString) ) def bidRequestHttpJsonMarshaller(implicit encoder: Encoder[BidRequest]): ToResponseMarshaller[BidRequest] = withFixedContentType(ContentTypes.`application/json`)( bidRequest => HttpResponse() .withEntity(HttpEntity(MediaTypes.`application/json`, encoder.apply(bidRequest).toString)) ) def bidResponseHttpJsonMarshaller(implicit encoder: Encoder[BidResponse]): ToResponseMarshaller[BidResponse] = withFixedContentType(ContentTypes.`application/json`)( bidResponse => HttpResponse() .withEntity(HttpEntity(MediaTypes.`application/json`, encoder.apply(bidResponse).toString)) ) }
Example 11
Source File: ZIODirectives.scala From full-scala-stack with Apache License 2.0 | 5 votes |
package api import akka.http.scaladsl.marshalling.{ Marshaller, Marshalling } import akka.http.scaladsl.model.HttpResponse import akka.http.scaladsl.server.{ Directive, Directive1, Route, RouteResult } import akka.http.scaladsl.marshalling.ToResponseMarshaller import akka.http.scaladsl.server.directives.RouteDirectives import akka.http.scaladsl.util.FastFuture._ import zio.{ DefaultRuntime, Task, ZIO } import scala.concurrent.{ Future, Promise } import scala.util.{ Failure, Success } def zioCompleteOrRecoverWith(magnet: ZIOCompleteOrRecoverWithMagnet): Directive1[Throwable] = magnet.directive } object ZIODirectives extends ZIODirectives trait ZIOCompleteOrRecoverWithMagnet { def directive: Directive1[Throwable] } object ZIOCompleteOrRecoverWithMagnet extends ZIODirectives { implicit def apply[T]( task: => Task[T] )(implicit m: ToResponseMarshaller[T]): ZIOCompleteOrRecoverWithMagnet = new ZIOCompleteOrRecoverWithMagnet { override val directive: Directive1[Throwable] = Directive[Tuple1[Throwable]] { inner => ctx => val future = unsafeRunToFuture(task) import ctx.executionContext future.fast.transformWith { case Success(res) => ctx.complete(res) case Failure(error) => inner(Tuple1(error))(ctx) } } } }