简体   繁体   English

将Spray Deserializer转换为Akka-Http Unarshaller

[英]Converting a Spray Deserializer to an Akka-Http Unarshaller

I have the following Deserializer from a Spray project that I'd like to port over to Akka-Http. 我有一个来自Spray项目的以下Deserializer ,我想移植到Akka-Http。 I'm just starting out with Akka-Http so I'm not to sure how I can port this code: 我只是从Akka-Http开始,所以我不确定如何移植此代码:

  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: 它过去使我可以将传入的url参数转换为应用程序的Enum类型,例如,这是一个利用Deserializer的隐式函数:

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

How would I accomplish the same thing in Akka-Http? 我如何在Akka-Http中完成相同的任务?

Figured this out. 想通了。 Akka has some pre-canned marrshallers like FromStringUnmarshaller that help out. Akka有一些罐头的marshaller,例如FromStringUnmarshaller可以提供帮助。 Here's how I converted my enum Deserializer to an Akka-Http UnMarshaller: 这是我将枚举反序列化器转换为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}"))
      }
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM