作为Argonaut`Json`的元帅akka`HttpResponse`

时间:2016-12-04 14:18:12

标签: scala akka akka-stream akka-http argonaut

我正在试图整理akka HttpResponse

{
  "code": 200,
  "headers": [],
  "body": "{\"data\": \"Yes!\"}"
}

如果我为此实例编写了一个Argonaut EncodeJson,它可能如下所示:

implicit def httpResponseEncodeJson: EncodeJson[HttpResponse] =
  EncodeJson(
    (res: HttpResponse) ⇒ {
      ("code" := res._1.value) ->:
      ("headers" := res._2.toList) ->:
      ("body" := res._3) ->: jEmptyObject
    }
  )

我设法将标题编组为json。唯一的问题是身体,即 ResponseEntity。因为它是akka流,所以如果我使用.toStrict,它只能返回未来。

有人可以指导我如何整理它吗?

2 个答案:

答案 0 :(得分:0)

如果可能,我会将编组值保持为Future,以保留实体提取的异步。

我会从

的方面开始
  case class StrictHttpResponse(code: String, headers: List[HttpHeader], body: String)

  def toStrictResponse(response: HttpResponse): Future[StrictHttpResponse] = response.entity.dataBytes.runFold(ByteString(""))(_ ++ _).map { bs =>
    StrictHttpResponse(response.status.value, response.headers.toList, bs.utf8String)
  }

  implicit def httpResponseEncodeJson: EncodeJson[StrictHttpResponse] =
    EncodeJson(
      (res: StrictHttpResponse) ⇒ {
        ("code" := res.code) ->:
          ("headers" := res.headers) ->:
          ("body" := res.body) ->: jEmptyObject
      }
    )

  def encodeResponse(response: HttpResponse): Future[Json] = toStrictResponse(response).map(_.jencode)

然后 - 例如 - 通过提供回调来处理encodeResponse的结果。

答案 1 :(得分:0)

我最终使用了这个:

  implicit def httpResponseListMarshal: ToEntityMarshaller[List[HttpResponse]] =
Marshaller { implicit ec ⇒ (responses: List[HttpResponse]) ⇒

    // Sink for folding Source of ByteString into 1 single huge ByteString
    val sink = Sink.fold[ByteString, ByteString](ByteString.empty)(_ ++ _)

    // A List of Future Json obtained by folding Source[ByteString]
    // and mapping appropriately
    val listFuture: List[Future[Json]] = for {
      res ← responses
    } yield for {
      byteString ← res._3.dataBytes runWith sink
      string = byteString.utf8String
    } yield ("code" := res._1.intValue) ->:
      ("headers" := res._2.toList) ->:
      ("body" := string) ->: jEmptyObject


    // Convert List[Future[Json]] to Future[List[Json]]
    val futureList: Future[List[Json]] = Future.sequence(listFuture)

    // ToEntityMarshaller is essentially a   Future[List[Marshalling[RequestEntity]]]
    for {
      list ← futureList
      json = jArray(list).nospaces
    } yield List(
      Marshalling.Opaque[RequestEntity](() ⇒
        HttpEntity(`application/json`, json)
    ).asInstanceOf[Marshalling[RequestEntity]]
  )
}

可以在此处找到完整的代码和示例用法: https://github.com/yashsriv/akka-http-batch-api/blob/argonaut/src/main/scala/org.yashsriv/json/Batch.scala