faraday timeout on a simple get
Asked Answered
C

3

16

Is there a way to add timeout options in this simple get method?

I am using Faraday 3.3.

Faraday.get(url)

After searching around, I can only apply timeout options after I initiate a connection first, then apply timeout options. Or there's a simple way?

This is what I am doing right now:

conn = Faraday.new
response = conn.get do |req|
  req.url url
  req.options.timeout = 2 # 2 seconds
end
Clef answered 28/8, 2015 at 13:35 Comment(0)
S
29

Try this one:

conn = Faraday.new do |conn|
  conn.options.timeout = 20
end
response = conn.get(url)

UPD: After I had reviewed gem sources, I found out that there's no way do it like you want.

With get method you can set only url, request params and headers. But to specify timeout, you have to access @options of Faraday::Connection instance. And you can do this by using attr_reader :options

conn = Faraday::Connection.new
conn.options.timeout = 20

Or on initialization of Faraday::Connection instance:

Faraday::Connection.new(nil, request: { timeout: 20 })

Or when it copies connection parameters to request parameter and yields request back:

Faraday::Connection.new.get(url) { |request| request.options.timeout = 20 }
Seedy answered 28/8, 2015 at 13:58 Comment(3)
thanks, this is similar to what I have. I was think if there's a way just pass the options in in the Faraday.get right away.Clef
Thanks so much for the clarification.Clef
There are other timeouts that can be set: I use open_timeout often, which is the timeout for opening the TCP connection. There's also a read_timeout and write_timeout, I think.Frontier
S
1

I had the same problem and I ended up doing something like this so I can more easily stub the code in testing:

    def self.get(url, params: {}, headers: {}, timeout: 2)
      conn = Faraday.new(
        params: params,
        headers: headers
      ) do |conn|
        conn.options.timeout = timeout
      end

      conn.get(url)
    end
Sanitize answered 26/1, 2023 at 14:37 Comment(0)
J
0

please refer to this official site: https://lostisland.github.io/faraday/#/customization/request-options

you can see in the request options there is 'timeout' and you can use it like this:

request_options = {
  timeout: 5
}

conn = Faraday.new(request: request_options) do |faraday|
  # ...
end
Jasminjasmina answered 19/7, 2024 at 6:29 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.