Skip to content

Instantly share code, notes, and snippets.

@dongw
Forked from robi42/rest.scala
Created February 24, 2012 15:29
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 dongw/1901640 to your computer and use it in GitHub Desktop.
Save dongw/1901640 to your computer and use it in GitHub Desktop.
Basic RESTful service with Finagle
class Respond extends Service[Request, Response] with Logger {
def apply(request: Request) = {
try {
request.method -> Path(request.path) match {
case GET -> Root / "todos" => Future.value {
val data = Todos.allAsJson
debug("data: %s" format data)
Responses.json(data, acceptsGzip(request))
}
case GET -> Root / "todos" / id => Future.value {
val todo = Todos get id
val data = todo.toJson
debug("data: %s" format data)
Responses.json(data, acceptsGzip(request))
}
case POST -> Root / "todos" => Future.value {
val content = request.contentString
val todo = Todos.fromJson(content, create = true)
val data = todo.toJson
Responses.json(data, acceptsGzip(request))
}
case PUT -> Root / "todos" / id => Future.value {
val content = request.contentString
val todo = Todos.fromJson(content, update = true)
val data = todo.toJson
debug("data: %s" format data)
Responses.json(data, acceptsGzip(request))
}
case DELETE -> Root / "todos" / id => Future.value {
Todos remove id
debug("data: %s" format id)
Response()
}
case _ =>
Future value Response(Http11, NotFound)
}
} catch {
case e: NoSuchElement => Future value Response(Http11, NotFound)
case e: Exception => Future.value {
val message = Option(e.getMessage) getOrElse "Something went wrong."
error("\nMessage: %s\nStack trace:\n%s"
.format(message, e.getStackTraceString))
Responses.error(message, acceptsGzip(request))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment