-
-
Save dongw/1901640 to your computer and use it in GitHub Desktop.
Basic RESTful service with 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[HttpRequest, HttpResponse] { | |
def apply(httpRequest: HttpRequest) = { | |
try { | |
val request = Request(httpRequest) | |
request.method -> Path(request.path) match { | |
case GET -> Root / "todos" => { | |
Future value Responses.json(Todos.allAsJson) | |
} | |
case GET -> Root / "todos" / id => { | |
val todo = Todos get id | |
Future value Responses.json(todo.toJson) | |
} | |
case POST -> Root / "todos" => { | |
val content = request.getContent.toString(UTF_8) | |
val todo = Todos.fromJson(content, create = true) | |
Future value Responses.json(todo.toJson) | |
} | |
case PUT -> Root / "todos" / id => { | |
val content = request.getContent.toString(UTF_8) | |
val todo = Todos.fromJson(content, update = true) | |
Future value Responses.json(todo.toJson) | |
} | |
case DELETE -> Root / "todos" / id => { | |
Todos remove id | |
Future value Responses.status(OK) | |
} | |
case _ => | |
Future value Responses.status(NOT_FOUND) | |
} | |
} catch { | |
case e: NoSuchElement => Future value Responses.status(NOT_FOUND) | |
case e: Exception => { | |
Future value Responses.error(e.getMessage) | |
throw e | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment