Created
October 19, 2018 16:51
-
-
Save andimiller/b2e32f8979b29cafa0eca6644f6884de to your computer and use it in GitHub Desktop.
sized decoder for http4s
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class Sized[T](bytes: Long, value: T) | |
object Sized { | |
implicit def sizedEntityDecoder[F[_] : FlatMap, T](implicit dec: EntityDecoder[F, T], F: Sync[F]): EntityDecoder[F, Sized[T]] = | |
new EntityDecoder[F, Sized[T]] { | |
override def decode(msg: Message[F], strict: Boolean): DecodeResult[F, Sized[T]] = { | |
EitherT( | |
for { | |
counter <- F.delay { | |
new LongAdder() | |
} | |
wrappedmsg <- F.delay { | |
msg.withEntity(msg.body.chunks.observe1(c => F.delay(counter.add(c.size.toLong)))) | |
} | |
result <- dec.decode(wrappedmsg, strict).value | |
sum <- F.delay { | |
counter.sum() | |
} | |
} yield result.map(x => Sized(sum, x)) | |
) | |
} | |
override def consumes: Set[MediaRange] = dec.consumes | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment