Reputation: 35
Many of directives (e.g., parameters) gives very convenient unmarshalling mechanism.
But I failed to find similar DSL for the Path Matcher from the documentation. I thought that given proper Unmarshaller, I would something like below,
implicit val userStatusUnmarshaller: FromStringUnmarshaller[UserStatus] = ???
val route = path("user" / Segment.as[UserStatus]) { status: UserStatus =>
...
}
expecially when the custom unmarshalling result is Enumeration.
Do they give such a way but I couldn't find or is there another way to do the same thing?
Upvotes: 0
Views: 1069
Reputation: 4017
What about implicitly extend PathMatcher1[String]
asking for something String => Option[T]
.
implicit class PimpedSegment(segment: PathMatcher1[String]) {
def as[T](implicit asT: String => Option[T]): PathMatcher1[T] =
segment.flatMap(asT)
}
For example you could implicitly require a JsonReader[T]
:
implicit class JsonSegment(segment: PathMatcher1[String]) {
def as[T: JsonReader]: PathMatcher1[T] = segment.flatMap { string =>
Try(JsString(string).convertTo[T]).toOption
}
}
Then it can be used as Segment.as[UserStatus]
.
Upvotes: 3
Reputation: 409
You can flatMap segment to UserStatus like so:
Segment.flatMap(UserStatus.fromString)
fromString
should return Option[UserStatus]
Upvotes: 6