4

I am using Vapor Swift to send GET / POST requests from the server-side using the below methods:

req.application.client.get(<#T##url: URI##URI#>, headers: <#T##HTTPHeaders#>, beforeSend: <#T##(inout ClientRequest) throws -> ()#>)
req.application.client.post(<#T##url: URI##URI#>, headers: <#T##HTTPHeaders#>, beforeSend: <#T##(inout ClientRequest) throws -> ()#>)

How do I set a timeout for the request? I could not find anything helpful in Vapor documentation.

I know Swift NIO has the scheduleTask feature, but I'm not too sure how to properly implement it. Some examples would be great!

let promise = req.eventLoop.makePromise(of: ClientResponse.self)
let timeoutSchedule = req.eventLoop.scheduleTask(in: .seconds(20)) {
    promise.fail(HTTPClientError.connectTimeout)
}
timeoutSchedule.cancel()
Wendell
  • 474
  • 3
  • 12
  • Do you want to delay the start of the request as `scheduleTask` does or do you want to change the timeout before it throws an error? – 0xTim Apr 26 '22 at 07:42
  • My goal is to stop the HTTP call after certain period of time because I have my app on HeroKu, which would throw an application error if my app doesn't do it, so I was think about 1) setting a timeout (if this attribute exists), or 2) somehow cancel the call in a scheduled task. Which one do you suggest? – Wendell Apr 27 '22 at 01:15
  • A scheduled task will only delay the start, it won't help with a timeout. I've answered – 0xTim Apr 27 '22 at 09:56

1 Answers1

3

Vapor does not expose a per request timeout on the client. You can drop down to use AsyncHTTPClient directly with request.application.http.client and use it per the docs to pass a timeout.

Alternatively you can set a global timeout in configure.swift with app.http.client.configuration.timeout. That defaults to a 10s connect timeout but no read timeout.

Finally you could also reduce the amount of data you're pulling down if the API supports something like pagination

0xTim
  • 5,146
  • 11
  • 23