vkt
vkt

Reputation: 1459

Transform Akka http entity byte string to Long

How to read long from an Akka-HTTP response stream of an unknown length?

example :

          val futureResponse = Http(system).singleRequest(
            HttpRequest(
              HttpMethods.POST,
              "url",
              entity = HttpEntity(ContentTypes.`application/json`, "somequery".getBytes())
            ).withHeaders(RawHeader("X-Access-Token", "access token"))
          )

          futureResponse.map {
            res =>
              res.entity.dataBytes
                .map(convertToLong) // convert to long/int
                .grouped(2) // group two elments together
                .map(getRelation)// do some transform
                .runWith(someSink) // write to sink

          }

how can we transform ByteString to the Long the above stream?

Upvotes: 0

Views: 336

Answers (1)

binkabir
binkabir

Reputation: 154

Write a function that takes a ByteString and return an option of a Long ByteString => Option[Long]

def toLong(x: ByteString): Option[Long] = {
 try{
     Some(x.decodeString("UTF-8").toLong)
     } catch {
      case e: Exception => None 
    }
}

Upvotes: 1

Related Questions