-
-
Save filipelenfers/5783113 to your computer and use it in GitHub Desktop.
Rest using Finagle
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
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