Skip to content

Instantly share code, notes, and snippets.

@BalmungSan
Created August 19, 2018 14:23
Show Gist options
  • Save BalmungSan/2b2fe66f63ecfb9fa7333342bee02820 to your computer and use it in GitHub Desktop.
Save BalmungSan/2b2fe66f63ecfb9fa7333342bee02820 to your computer and use it in GitHub Desktop.
Http4s EntityEncoder for returning Streams as JSONArrays using Circe.
import cats.Applicative
import cats.effect.IO
import fs2.Stream
import io.circe.Encoder
import io.circe.generic.semiauto.deriveEncoder
import io.circe.syntax.EncoderOps
import org.http4s.{EntityEncoder, MediaType}
import org.http4s.dsl.io._
import org.http4s.headers.`Content-Type`
import scala.language.higherKinds
/** EntityEncoder for Streams of T values, which will encode them as a JSONArrays */
implicit def streamAsJsonArrayEncoder[F[_], T](implicit F: Applicative[F], tEncoder: Encoder[T]): EntityEncoder[F, Stream[F, T]] =
EntityEncoder
.streamEncoder[F, String]
.contramap[Stream[F, T]](stream => Stream.emit("[") ++ stream.map(t => t.asJson.noSpaces).intersperse(",") ++ Stream.emit("]"))
.withContentType(`Content-Type`(MediaType.`application/json`))
/** Simple case class */
final case class Data(
id: Int,
name: String
)
/** Circe JSON encoder for our simple case class */
implicit val dataCirceEncoder: Encoder[Data] = deriveEncoder
/** Test the Encoder */
Ok(Stream(Data(id = 3, name = "BalmungSan"), Data(id = 5, name = "Luis Miguel Mejía Suárez")).covary[IO]).unsafeRunSync
// Response(status=200, headers=Headers(Transfer-Encoding: chunked, Content-Type: application/json))
// Body: "[{"id":3,"name":"BalmungSan"},{"id":5,"name":"Luis Miguel Mejía Suárez"}]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment