Last active
August 29, 2015 14:19
-
-
Save davidhoyt/5421730fe6202c9cc20e to your computer and use it in GitHub Desktop.
Spray multimap for form fields and parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type MultiMap = Map[String, List[String]] | |
def formFieldMultiMap: Directive1[MultiMap] = { | |
requestInstance.flatMap[MultiMap :: HNil] { request => | |
import spray.httpx.unmarshalling._ | |
val result: Deserialized[MultiMap] = | |
request.as[HttpForm].right.flatMap { | |
case FormData(fields) => | |
val collected = fields.groupBy { case (k, _) => k } | |
val valuesOnly = collected.mapValues(_.map { case (_, v) => v } toList) | |
Right(valuesOnly) | |
case _ => | |
Left(MalformedContent(s"Unable to construct form multi map")) | |
} | |
result match { | |
case Right(value) ⇒ provide(value) | |
case Left(ContentExpected) ⇒ reject(MissingFormFieldRejection("form")) | |
case Left(MalformedContent(msg, cause)) ⇒ reject(MalformedFormFieldRejection("form", msg, cause)) | |
case Left(UnsupportedContentType(msg)) ⇒ reject(UnsupportedRequestContentTypeRejection(msg)) | |
} | |
} | |
} | |
def anyMultiMap: Directive1[MultiMap] = | |
for { | |
params <- parameterMultiMap | |
fields <- formFieldMultiMap | |
} yield fields.foldLeft(params) { | |
case (map, (fk, fv)) if map.contains(fk) => | |
map.updated(fk, map(fk) ++ fv) | |
case (map, field) => | |
map + field | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment