Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5a1990a

Browse files
Adds timeout to requests (#223)
1 parent b1e14bd commit 5a1990a

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

lib/discourse_api/client.rb

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ module DiscourseApi
2929
class Client
3030
attr_accessor :api_key
3131
attr_accessor :basic_auth
32-
attr_reader :host, :api_username
32+
attr_reader :host, :api_username, :timeout
33+
34+
DEFAULT_TIMEOUT = 30
3335

3436
include DiscourseApi::API::Categories
3537
include DiscourseApi::API::Search
@@ -60,6 +62,11 @@ def initialize(host, api_key = nil, api_username = nil)
6062
@use_relative = check_subdirectory(host)
6163
end
6264

65+
def timeout=(timeout)
66+
@timeout = timeout
67+
@connection.options.timeout = timeout if @connection
68+
end
69+
6370
def api_username=(api_username)
6471
@api_username = api_username
6572
@connection.headers['Api-Username'] = api_username unless @connection.nil?
@@ -68,6 +75,9 @@ def api_username=(api_username)
6875
def connection_options
6976
@connection_options ||= {
7077
url: @host,
78+
request: {
79+
timeout: @timeout || DEFAULT_TIMEOUT
80+
},
7181
headers: {
7282
accept: 'application/json',
7383
user_agent: user_agent,
@@ -158,6 +168,8 @@ def request(method, path, params = {})
158168
response.env
159169
rescue Faraday::ClientError, JSON::ParserError
160170
raise DiscourseApi::Error
171+
rescue Faraday::ConnectionFailed
172+
raise DiscourseApi::Timeout
161173
end
162174

163175
def handle_error(response)

lib/discourse_api/error.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,7 @@ class UnprocessableEntity < DiscourseError
3333

3434
class TooManyRequests < DiscourseError
3535
end
36+
37+
class Timeout < DiscourseError
38+
end
3639
end

spec/discourse_api/client_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,21 @@
2828
end
2929
end
3030

31+
describe "#timeout" do
32+
context 'custom timeout' do
33+
it "is set to Faraday connection" do
34+
expect(subject.send(:connection).options.timeout).to eq(30)
35+
end
36+
end
37+
38+
context 'default timeout' do
39+
it "is set to Faraday connection" do
40+
subject.timeout = 25
41+
expect(subject.send(:connection).options.timeout).to eq(25)
42+
end
43+
end
44+
end
45+
3146
describe "#api_key" do
3247
it "is publically accessible" do
3348
subject.api_key = "test_d7fd0429940"

0 commit comments

Comments
 (0)