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()
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