tethys-json / tethys

AST free JSON library for Scala
https://tethys-json.github.io/tethys/
Apache License 2.0
110 stars 34 forks source link

akka-http integration #4

Open eld0727 opened 7 years ago

NikitaMelnikov commented 7 years ago

Hm...

This code should be enough to implement Tethys support in akka-http I think:

import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller}
import akka.http.scaladsl.model.ContentTypeRange
import akka.http.scaladsl.model.MediaTypes.`application/json`
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller}
import akka.util.ByteString
import tethys._
import tethys.jackson._

import scala.reflect.ClassTag

trait TethysSupport {
  lazy val unmarshallerContentTypes: Seq[ContentTypeRange] = List(`application/json`)

  implicit def unmarshaller[A](implicit reader: JsonReader[A]): FromEntityUnmarshaller[A] = {
    Unmarshaller.byteStringUnmarshaller
      .forContentTypes(unmarshallerContentTypes: _*)
      .mapWithCharset {
        case (ByteString.empty, _) => throw Unmarshaller.NoContentException
        case (data, charset) => data.decodeString(charset.nioCharset.name).jsonAs[A].fold(throw _, identity)
      }
  }

  implicit def marshaller[A](implicit ct: ClassTag[A], writer: JsonWriter[A]): ToEntityMarshaller[A] = {
    Marshaller.stringMarshaller(`application/json`).compose(_.asJson)
  }
}

Show we place it as separated module or just as an example?

Odomontois commented 5 years ago

Is there some concern about suggesting PR to https://github.com/hseeberger/akka-http-json? It's a perfect place for such a module, isn't it?