Last active
August 26, 2017 21:10
-
-
Save marcintustin/331d8c12f058866358cdd3e2e358c913 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
val service = HttpService { | |
// pure example | |
case GET -> Root / "hello" / name => | |
Ok(Json.obj("message" -> Json.fromString(s"Hello, ${name}"))) | |
case request @ POST -> Root / "hello" / name => | |
for { | |
// Decode a user request - simplest way to access the request body | |
greeting <- request.as(jsonOf[Greeting]) | |
resp <- Ok(Json.obj("message" -> Json.fromString(s"${greeting.greeting}, ${name}"))) | |
} yield resp | |
case request @ PUT -> Root / "hello" / name => { | |
// request.as returns a Task; attempt converts it to a task that | |
// will return a (scalaz) Either (\/) of either a throwable or the result | |
// Use flatMap here rather than map, because flatMap allows you to return | |
// the objects wrapped in a Task that the http4s api provides, and they flatten | |
// to one level of Task, rather than a Task[Task[Response]] as they would with | |
// simple map. | |
// If you're integrating with FS2-based code, map may be better | |
request.as(jsonOf[ExtendedGreeting]).attempt.flatMap { | |
// check that the exception is caused by a decoding failure | |
// and use the Circe show capabilities to print out a vaguely | |
// useful error message in the response | |
case -\/(f) => f.getCause match { | |
case (d: DecodingFailure) => BadRequest(d.show) | |
case _ => BadRequest(f.toString) | |
} | |
// Handle the happy path | |
case \/-(greeting) => Ok(Json.obj("message" -> Json.fromString(s"${greeting.greeting.greeting}, ${name}"))) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment