Skip to content

Instantly share code, notes, and snippets.

@withoutclass
Last active December 14, 2017 15:19
Show Gist options
  • Save withoutclass/191923a1300b2cfd449906a286300324 to your computer and use it in GitHub Desktop.
Save withoutclass/191923a1300b2cfd449906a286300324 to your computer and use it in GitHub Desktop.
Vertx API without awaitResult
class App : CoroutineVerticle() {
suspend override fun start() {
... // setup
router.post("/ingredientCR").coroutineHandler { ctx -> addIngredientCoroutine(ctx) }
awaitResult<HttpServer> {
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(config.getInteger("http.port", 8080), it)
}
}
private suspend fun addIngredientCoroutine(ctx: RoutingContext) {
val ingredientName = ctx.bodyAsJson.getString("name")
val ingredientQuantity = ctx.bodyAsJson.getInteger("quantity")
val id = ThreadLocalRandom.current().nextLong()
val insertResult = ingredientDao.insertIngredient(ingredient = Ingredient(id = id,
name = ingredientName,
quantity = ingredientQuantity))
yield()
if (insertResult) {
val ingredient = ingredientDao.selectIngredient(id)
yield()
ctx.response().end(json {
obj("id" to ingredient.id, "name" to ingredient.name, "quantity" to ingredient.quantity).encode()
})
} else {
ctx.response().setStatusCode(500).end("Failed to insert new ingredient")
}
}
}
fun Route.coroutineHandler(fn: suspend (RoutingContext) -> Unit) {
handler { ctx ->
launch(ctx.vertx().dispatcher()) {
try {
fn(ctx)
} catch (e: Exception) {
ctx.fail(e)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment