Skip to content

Instantly share code, notes, and snippets.

@dalegaspi
Created February 25, 2019 20:47
Show Gist options
  • Save dalegaspi/6217c7b6577b8b81df7a4df2a398eb29 to your computer and use it in GitHub Desktop.
Save dalegaspi/6217c7b6577b8b81df7a4df2a398eb29 to your computer and use it in GitHub Desktop.
A mixin trait for using PBDirect with Akka HTTP for Protobuf support
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