Converting a Spray Deserializer to an Akka-Http Unarshaller

63 views Asked by At

I have the following Deserializer from a Spray project that I'd like to port over to Akka-Http. I'm just starting out with Akka-Http so I'm not to sure how I can port this code:

  class urlParameterEnumDeserializer[T](enum: AppEnum[T]) extends Deserializer[String, T] {
    def apply(s: String) = {
      enum.valueOf(s).toRight(MalformedContent(s"Expected a valid string for ${enum} conversion. Found: ${s}"))
    }
  }

It used to allow me to convert incoming url parameters to my application's Enum types, for instance here's an implicit function that utilizes the Deserializer:

implicit val contentSourceDeserializer = new urlParameterEnumDeserializer[ContentSource](ContentSource)

How would I accomplish the same thing in Akka-Http?

1

There are 1 answers

0
ThaDon On BEST ANSWER

Figured this out. Akka has some pre-canned marrshallers like FromStringUnmarshaller that help out. Here's how I converted my enum Deserializer to an Akka-Http UnMarshaller:

  class urlParameterCrowdscriberEnumDeserializer[T](enum: CrowdscriberEnum[T]) extends FromStringUnmarshaller[T] {
    override def apply(s: String)(implicit ec: ExecutionContext, materializer: Materializer): Future[T] = {
      enum.valueOf(s) match {
        case Some(e) => FastFuture.successful(e)
        case None => FastFuture.failed(new IllegalArgumentException(s"Expected a valid string for ${enum} conversion. Found: ${s}"))
      }
    }
  }