akka-http 自定义 PathMatcher
akka-http custom PathMatcher
许多指令(例如,parameters)提供了非常方便的解组机制。
但是我没能从文档中找到 Path Matcher 的类似 DSL。
我认为如果有适当的 Unmarshaller,我会像下面这样,
implicit val userStatusUnmarshaller: FromStringUnmarshaller[UserStatus] = ???
val route = path("user" / Segment.as[UserStatus]) { status: UserStatus =>
...
}
特别是当自定义解组结果为枚举时。
他们是否提供了这样的方法但我找不到,或者是否有其他方法可以做同样的事情?
您可以像这样将 flatMap 分段到 UserStatus:
Segment.flatMap(UserStatus.fromString)
fromString
应该 return Option[UserStatus]
隐式扩展 PathMatcher1[String]
要求什么 String => Option[T]
。
implicit class PimpedSegment(segment: PathMatcher1[String]) {
def as[T](implicit asT: String => Option[T]): PathMatcher1[T] =
segment.flatMap(asT)
}
例如,您可以隐式要求 JsonReader[T]
:
implicit class JsonSegment(segment: PathMatcher1[String]) {
def as[T: JsonReader]: PathMatcher1[T] = segment.flatMap { string =>
Try(JsString(string).convertTo[T]).toOption
}
}
那么可以作为Segment.as[UserStatus]
.
许多指令(例如,parameters)提供了非常方便的解组机制。
但是我没能从文档中找到 Path Matcher 的类似 DSL。 我认为如果有适当的 Unmarshaller,我会像下面这样,
implicit val userStatusUnmarshaller: FromStringUnmarshaller[UserStatus] = ???
val route = path("user" / Segment.as[UserStatus]) { status: UserStatus =>
...
}
特别是当自定义解组结果为枚举时。
他们是否提供了这样的方法但我找不到,或者是否有其他方法可以做同样的事情?
您可以像这样将 flatMap 分段到 UserStatus:
Segment.flatMap(UserStatus.fromString)
fromString
应该 return Option[UserStatus]
隐式扩展 PathMatcher1[String]
要求什么 String => Option[T]
。
implicit class PimpedSegment(segment: PathMatcher1[String]) {
def as[T](implicit asT: String => Option[T]): PathMatcher1[T] =
segment.flatMap(asT)
}
例如,您可以隐式要求 JsonReader[T]
:
implicit class JsonSegment(segment: PathMatcher1[String]) {
def as[T: JsonReader]: PathMatcher1[T] = segment.flatMap { string =>
Try(JsString(string).convertTo[T]).toOption
}
}
那么可以作为Segment.as[UserStatus]
.