Igor Yudnikov
Igor Yudnikov

Reputation: 464

Akka HTTP route post entity string, complete with Future

I have an Akka HTTP daemon. Assume that I want to receive some client data in JSON format and save it into a database asynchronously. I wrote a route in a POST branch:

path("product") {
  entity(as[String]) { json =>
    val saveFuture: Future[Unit] = Serialization.read[Product](json).save()
    complete("")
  }
}

I've found that complete can be put into an onSuccess statement like:

path("success") {
  onSuccess(Future { "Ok" }) { extraction =>
    complete(extraction)
  }
}

But I can't understand how to glue them together.

Upvotes: 0

Views: 867

Answers (1)

Jeffrey Chung
Jeffrey Chung

Reputation: 19517

You can nest the directives:

path("product") {
  entity(as[String]) { json =>
    val saveFuture: Future[Unit] = Serialization.read[Product](json).save()
    onSuccess(saveFuture) {
      complete("json was saved")
    }
  }
}

Upvotes: 2

Related Questions