Skip to content

Instantly share code, notes, and snippets.

@ches
Last active December 15, 2016 08:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ches/c8835bc9753ccc3ca42a to your computer and use it in GitHub Desktop.
Save ches/c8835bc9753ccc3ca42a to your computer and use it in GitHub Desktop.
spray implicit allowing spray DateTimes to be deserialized from parameters directives
import spray.http.DateTime
import spray.httpx.unmarshalling._
/*
* Implicit allowing spray DateTimes to be deserialized from parameters directives.
*
* See: http://spray.io/documentation/1.2.2/spray-httpx/unmarshalling/
*/
// type FromStringOptionDeserializer[T] = Deserializer[Option[String], T]
implicit def string2DateTime = new FromStringOptionDeserializer[DateTime] {
def apply(value: Option[String]): Deserialized[DateTime] = value match {
case None => Left(ContentExpected)
case Some(str) =>
DateTime.fromIsoDateTimeString(str) toRight (new MalformedContent("invalid datetime format"))
}
}
// This is equivalent, by virtue of `fromFunction2Converter` (which wraps the
// unsafe `get` here in a try), and the Option-lifting implicits found in
// `spray.httpx.unmarshalling.Deserializer`. Lotsa magic.
implicit def string2DateTime(str: String): DateTime =
DateTime.fromIsoDateTimeString(str).get
val route =
path("something") {
get {
parameters('start.as[DateTime], 'end.as[DateTime]) { (start, end) =>
// ...
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment