Skip to content

Instantly share code, notes, and snippets.

@sam
Created December 2, 2016 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sam/7a7373d6d4f46975f5c022a8b7fba83c to your computer and use it in GitHub Desktop.
Save sam/7a7373d6d4f46975f5c022a8b7fba83c to your computer and use it in GitHub Desktop.
When receiving a multipart POST, parse the application/json part into an entity, and capture the file upload.
pathEndOrSingleSlash {
(post & parameter("rev")) { rev =>
// This is very important, so we can provide a more specific
// implicit to overcome the Json4sSupport default unmarshaller
// that will require an `application/json` ContentType!
import Unmarshaller._
entity(as[Multipart.General]) { body =>
import scala.concurrent.duration._
onSuccess {
body.parts.runFoldAsync((Option.empty[CreateMailer], Option.empty[TemporaryFile])) {
case ((_, file), part) if part.entity.contentType.mediaType == `application/json` =>
part.entity.toStrict(30 seconds).map { strict =>
// serialization.read expects an implicit org.json4s.Formats and Manifest[T]
(serialization.read(strict.data.decodeString(StandardCharsets.UTF_8)), file)
}
case ((value, _), part) =>
val tmp = File.createTempFile("upload", "tmp")
tmp.deleteOnExit()
part.entity.dataBytes.runWith(FileIO.toPath(tmp.toPath)).map { _ =>
value -> Option(TemporaryFile(part.entity.contentType.mediaType,
None,
tmp.length(),
tmp))
}
}
} {
case (Some(create), Some(upload)) =>
onSuccess(events ? (eventId.revise(rev), create, upload)) {
case status: ClientError => complete(status, JNothing)
case key: IdWithRev => complete(StatusCodes.Created -> decompose(key))
}
case _ => reject
}
reject
} ~ entity(as[CreateMailer]) { create =>
onSuccess(events ? (eventId.revise(rev), create)) {
case status: ClientError => complete(status, JNothing)
case key: IdWithRev => complete(StatusCodes.Created -> decompose(key))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment