So I have a POST route that takes a request body a...
# ktor
c
So I have a POST route that takes a request body and then makes its own post call to a third party server. if that request is successful, i want to respond to the original request with a 200 OK status. I can't quite figure out how to do that. I can make the post to the third party and its successful because i see the data being received in the third party just fine but i can't figure out how to get the status back in my code for the call to the third party so i can report it in my response to the original request
m
Something like this:
Copy code
post('/foo') {
   val response = async {
       someHttpClient.doSomeRequest('<https://bar.com/quux>')
   }.await()

   if (response.statusCode == 200) {
       call.respond(HttpStatus.Ok)
   } else {
       call.respond(HttpStatus.InternalError)
   }
}
c
val response
ends up returning unit and there's nothing i can call on it
wait, maybe not. I think i found a typo
Man, that did it after all. I was way overcomplicating things in my head
lots of little subtle things i was doing wrong that made me try even more wrong things and just getting lost down a rabbit hole. Thank you so much!
d
The async block isn't needed if its already a non blocking client like Ktor client though...
⏸️ 1
2
g
also such idiom as
async{}.await()
already wrong itself, there are no cases when you need this
2
m
Well, I’m skipping a few things — I don’t claim that sample compiles 🙂 If the function that does http things is
suspend
, then you don’t need
async
etc. If it returns
CompletableFuture
or similar, then you would.
(to be pedantic in that case,
CompletionStage#asDeferred
IIRC. Or if it’s blocking, then more ceremony is required...)
g
If it returns
CompletableFuture
or similar, then you would.
But it will be
CompletableFuture.await()
extension, not a
Deffered.await()
m
Ah, true
g
if it’s blocking, then more ceremony is required
Not so much and also await() is not needed in this case
Copy code
val result = withContext(IO) { someBlockingCall() }
m
Oh, assuming you don’t want to do something else while the call is running, sure
g
exactly, if you do concurrent calls, you need
async{}
, but in this case you never call it as
async{}.await()
because it make impossible to run a few concrrent tasks You would do rather something like:
Copy code
val a = async{}
val b = async{}
a.await() + b.await()
m
Yep. Good to point that out; I should have made that more clear in a comment or something.