Created
February 25, 2019 20:47
-
-
Save dalegaspi/6217c7b6577b8b81df7a4df2a398eb29 to your computer and use it in GitHub Desktop.
A mixin trait for using PBDirect with Akka HTTP for Protobuf support
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
import akka.http.scaladsl.marshalling.{Marshaller, ToEntityMarshaller} | |
import akka.http.scaladsl.model.MediaType.{NotCompressible, applicationBinary} | |
import akka.http.scaladsl.model.{ContentTypeRange, MediaType} | |
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, Unmarshaller} | |
import pbdirect._ | |
/** | |
* This allows you to have a mixin trait for use with Akka HTTP endpoints that accept/return Protobuf. | |
* This has been patterned after https://github.com/hseeberger/akka-http-json and uses | |
* https://github.com/btlines/pbdirect for "proto-less" (i.e. no .proto schemas) serialization/ | |
* deserializaition of case classes | |
* | |
* Note that this uses the media type "application/protobuf". | |
*/ | |
trait ProtobufSupport { | |
def unmarshallerContentTypes: Seq[ContentTypeRange] = | |
mediaTypes.map(ContentTypeRange.apply) | |
def mediaTypes: Seq[MediaType.Binary] = | |
List(applicationBinary("protobuf", NotCompressible)) | |
private val unmarshaller = Unmarshaller.byteArrayUnmarshaller | |
.forContentTypes(unmarshallerContentTypes: _*) | |
// this is from the pbdirect README. an example of how to add PB support to a Java class | |
import cats.syntax.invariant._ | |
implicit val instantFormat: PBFormat[java.net.URI] = | |
PBFormat[String].imap(s => new java.net.URI(s))(u => u.toString) | |
implicit def protobufMarshaller[T <: AnyRef](implicit writer: PBWriter[T]): ToEntityMarshaller[T] = | |
Marshaller.byteArrayMarshaller(applicationBinary("protobuf", NotCompressible)).compose(_.toPB) | |
implicit def protobufUnmarshaller[T <: AnyRef](implicit reader: PBParser[T]): FromEntityUnmarshaller[T] = | |
unmarshaller.map(b => b.pbTo[T]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment