Question about blockingOp vs blockingMap (1.0.0-rc-3)

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

Question about blockingOp vs blockingMap (1.0.0-rc-3)

dennytron
Hi there! I have a question about the proper way to implement blocking processes in Ratpack. I’m fairly new to Ratpack and asynchronous data processing.

I’m using Ratpack 1.0.0-rc-3 and Groovy to create a REST API. The API is simple, and it only supports GET on one URL endpoint and PUT on a different URL endpoint.

For the GET, the code simply fetches a row from a Postgres database, converts the row to JSON, and sends that data back to the user. It can execute asynchronously.

For the PUT, the code reads JSON and updates a row in the Postgres database. I want the code to block other PUT requests until it is finished updating the database with its current request.

Should I use “blockingOp” or “blockingMap” on the Promise to implement blocking in the PUT portion of the code below? I’m unclear about the difference between the two.

prefix("get/endpoint") {
        all { ctx ->
                ctx.byMethod {
                        get {
                                // fetch and send the record
                                response.send("some json")
                        }
                }
        }
}

prefix("put/endpoint") {
        all { ctx ->
                ctx.byMethod {
                        put {
                                request.body.blockingOp { body ->
                                        // process the body, send a message
                                        String requestBody = body.text
                                        response.send("some message")
                                }.then {}

                        }
                }
        }
}

I'm assembling this code based on Ratpack examples I've found online.

Thanks for any help!

Dennis
Reply | Threaded
Open this post in threaded view
|

Re: Question about blockingOp vs blockingMap (1.0.0-rc-3)

danhyun
The difference between an Operation and a Promise is that Operation does not care about return types. If your blocking operation does not need to return anything that simply use `blockingOp`.

I would actually do something like this for your put method.

 put {
  request.body.map { body ->
    body.text
  }.blockingOp {text ->
    // store text
  }.then {
    render "some message"
  }
}
Reply | Threaded
Open this post in threaded view
|

Re: Question about blockingOp vs blockingMap (1.0.0-rc-3)

dennytron
@danhyun  

Ah! Understood. That makes sense, and your example is very clear.  

Thank you very much!

Dennis