Last active
June 16, 2016 04:43
-
-
Save mankyKitty/ac280a820ced31b3511159acd0a09bbf to your computer and use it in GitHub Desktop.
Scala - Argonaut - FUNfiltered
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
// The Argonaut docs are quite good at showing how to setup | |
// the various instances that power all of this jazz, but for | |
// the sake of discussion I'll include one of the simplest ones | |
// for just whipping up the required implicits. | |
final case class Wibble ( | |
id: Double, // Because MUAHAHAHAHA | |
wut: String, | |
wat: List[Int] | |
) | |
// This little turd will create the [EncodeJson] and | |
// [DecodeJson] pieces for use with argonaut. | |
implicit def wibbleCodec = casecodec3( | |
Wibble.apply, Wibble.unapply | |
)( | |
"id", | |
"wut", | |
"wat" | |
) | |
// We tend to wrap up the type that Unfiltered throws at us | |
// with a custom type: | |
type Request = HttpRequest[unfiltered.netty.ReceivedMessage] | |
type ReqAsync = HttpRequest[unfiltered.netty.ReceivedMessage] | |
with unfiltered.Async.Responder[NHttpResponse] | |
type Response = ResponseFunction[NHttpResponse] | |
// YMMV though, depending on how you're structuring your app. | |
// We sort of do the decode in two stages, since we don't always | |
// give a damn about the contents of the message. We use a class | |
// to hide it all away... | |
class RequestAsync(val req: ReqAsync) { | |
// This just packages up the content of the request into raw | |
// [Json], well, it might, if you look at it. We have things | |
// that just pass this stuff through so it's a nice warm fuzzy | |
// feeling that something else is checking you've passed in legit | |
// json data | |
lazy val json = JsonRequest(req).decode[Json] | |
// This sucker does the dirty work. Forcing our lazy json (hate that guy) | |
// and trying to make it into the thing that has the [DecodeJson] instance/implicit/class/val/thing.. scala(TM) | |
def decode[A:DecodeJson]: (String \/ (String, CursorHistory)) \/ A = | |
json.flatMap( _.as[A].result.leftMap( \/.right(_) )) | |
// We have a bunch of other helper methods on this thing, if you | |
// want or need things like [fromHeader,params,uri,method] etc. | |
} | |
// When you're actually calling the decode to get the thing you're after... | |
def unwibble(req: RequestAsync): MahMoonad[Response] | |
for { | |
a <- req.decode[Wibble] | |
r <- unWibble(a) | |
} yield Ok ~> JsonResponse( Map("Unwibbled" -> r) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment