Skip to content

Instantly share code, notes, and snippets.

@danclien
Last active December 20, 2015 21:59
Show Gist options
  • Save danclien/6202033 to your computer and use it in GitHub Desktop.
Save danclien/6202033 to your computer and use it in GitHub Desktop.
import scala.concurrent.duration.Duration
import spray.routing.HttpService
import spray.routing.authentication.BasicAuth
import spray.routing.directives.CachingDirectives._
import spray.httpx.encoding._
trait LongerService extends HttpService with MyApp {
val simpleCache = routeCache(maxCapacity = 1000, timeToIdle = Duration("30 min"))
val route = {
path("orders") {
authenticate(BasicAuth(realm = "admin area")) { user =>
get {
cache(simpleCache) {
encodeResponse(Deflate) {
complete {
// marshal custom object with in-scope marshaller
getOrdersFromDB
}
}
}
} ~
post {
(decodeRequest(Gzip) | decodeRequest(NoEncoding)) {
// unmarshal with in-scope unmarshaller
entity(as[Order]) { order =>
// transfer to newly spawned actor
detachTo(singleRequestServiceActor) {
complete {
// ... write order to DB
"Order received"
}
}
}
}
}
}
} ~
// extract URI path element as Int
pathPrefix("order" / IntNumber) { orderId =>
path("") {
// method tunneling via query param
(put | parameter('method ! "put")) {
// form extraction from multipart or www-url-encoded forms
formFields('email, 'total.as[Money]).as(Order) { order =>
complete {
// complete with serialized Future result
(myDbActor ? Update(order)).mapTo[TransactionResult]
}
}
} ~
get {
// JSONP support
jsonpWithParameter("callback") {
// use in-scope marshaller to create completer function
produce(instanceOf[Order]) { complete => ctx =>
processOrderRequest(orderId, complete)
}
}
}
} ~
path("items") {
get {
// parameters to case class extraction
parameters('size.as[Int], 'color ?, 'dangerous ? "no")
.as(OrderItem) { orderItem =>
// ... route using case class instance created from
// required and optional query parameters
}
}
}
} ~
path("documentation") {
// cache responses to GET requests
cache(simpleCache) {
// serve up static content from a JAR resource
encodeResponse(Gzip) {
getFromResourceDirectory("docs")
}
}
} ~
path("oldApi" / Rest) { path =>
redirect("http://oldapi.example.com/" + path, StatusCodes.MovedPermanently)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment