Skip to content

Instantly share code, notes, and snippets.

@robi42
Created September 23, 2011 15:55
Show Gist options
  • Save robi42/1237735 to your computer and use it in GitHub Desktop.
Save robi42/1237735 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