5

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()
3
  • 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? Commented Apr 26, 2022 at 7: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? Commented Apr 27, 2022 at 1:15
  • A scheduled task will only delay the start, it won't help with a timeout. I've answered Commented Apr 27, 2022 at 9:56

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.