Asynchronous Body Parsing

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Asynchronous Body Parsing

danthegoodman
I am happy to see asynchronous body parsing in the latest version of ratpack! Good job, ratpack team!

So I've been churning through our services and upgrading them. I find that I've been writing this pattern of code a lot, as most of my services touch a database that still uses a blocking api:

    context.parse(json(Map)).flatMap { body ->
      //process body
      Blocking.get {
        //database save
      }
    }.then {
      context.render("ok")
    }

I suppose this pattern is okay, but I would prefer something  less nested. I seem to remember a 'blockingMap' existing as a method on the promise not too long ago, but it doesn't appear to be around anymore.  What do you think about bringing it back? I would prefer to see code along these lines:

    context.parse(json(Map)).map { body ->
      //process body
    } blockingMap {
      //database save
    } then {
      context.render("ok")
    }
Reply | Threaded
Open this post in threaded view
|

Re: Asynchronous Body Parsing

Luke Daley
Administrator
Ask an ye shall receive: https://github.com/ratpack/ratpack/commit/a3ed78885cd07d623f83c295d7fa4b80b4c975e8

BTW, if you want to avoid nesting for some operation that we don't support you can use http://ratpack.io/manual/current/api/ratpack/exec/Promise.html#apply-ratpack.func.Function-

class CustomOps {
  <O>  Promise<O> save(Promise<T> promise) {
    promise.flatMap { t ->
      Blocking.get  { t.save() }
    }  
  }
}

Promise.value(thing).apply(CustomOps.&save).then { }

Or…

class CustomOps {
  <O>  Function<Promise<T>, Promise<O>> save() {
    return { it.flatMap { t ->
        Blocking.get  { t.save() }
      }
    }  
  }
}

Promise.value(thing).apply(CustomOps.save()).then { }
Reply | Threaded
Open this post in threaded view
|

Re: Asynchronous Body Parsing

danthegoodman
This is great! Thank you!