Adds timeout to requests (#223)

Adds timeout to requests (#223)

diff --git a/lib/discourse_api/client.rb b/lib/discourse_api/client.rb
index 8ed0aba..fcf0a33 100644
--- a/lib/discourse_api/client.rb
+++ b/lib/discourse_api/client.rb
@@ -29,7 +29,9 @@ module DiscourseApi
   class Client
     attr_accessor :api_key
     attr_accessor :basic_auth
-    attr_reader :host, :api_username
+    attr_reader :host, :api_username, :timeout
+
+    DEFAULT_TIMEOUT = 30
 
     include DiscourseApi::API::Categories
     include DiscourseApi::API::Search
@@ -60,6 +62,11 @@ module DiscourseApi
       @use_relative = check_subdirectory(host)
     end
 
+    def timeout=(timeout)
+      @timeout = timeout
+      @connection.options.timeout = timeout if @connection
+    end
+
     def api_username=(api_username)
       @api_username = api_username
       @connection.headers['Api-Username'] = api_username unless @connection.nil?
@@ -68,6 +75,9 @@ module DiscourseApi
     def connection_options
       @connection_options ||= {
         url: @host,
+        request: {
+          timeout: @timeout || DEFAULT_TIMEOUT
+        },
         headers: {
           accept: 'application/json',
           user_agent: user_agent,
@@ -158,6 +168,8 @@ module DiscourseApi
       response.env
     rescue Faraday::ClientError, JSON::ParserError
       raise DiscourseApi::Error
+    rescue Faraday::ConnectionFailed
+      raise DiscourseApi::Timeout
     end
 
     def handle_error(response)
diff --git a/lib/discourse_api/error.rb b/lib/discourse_api/error.rb
index 2760720..5e6f554 100644
--- a/lib/discourse_api/error.rb
+++ b/lib/discourse_api/error.rb
@@ -33,4 +33,7 @@ module DiscourseApi
 
   class TooManyRequests < DiscourseError
   end
+
+  class Timeout < DiscourseError
+  end
 end
diff --git a/spec/discourse_api/client_spec.rb b/spec/discourse_api/client_spec.rb
index fbd6bbe..7bcdbfd 100644
--- a/spec/discourse_api/client_spec.rb
+++ b/spec/discourse_api/client_spec.rb
@@ -28,6 +28,21 @@ describe DiscourseApi::Client do
     end
   end
 
+  describe "#timeout" do
+    context 'custom timeout' do
+      it "is set to Faraday connection" do
+        expect(subject.send(:connection).options.timeout).to eq(30)
+      end
+    end
+
+    context 'default timeout' do
+      it "is set to Faraday connection" do
+        subject.timeout = 25
+        expect(subject.send(:connection).options.timeout).to eq(25)
+      end
+    end
+  end
+
   describe "#api_key" do
     it "is publically accessible" do
       subject.api_key = "test_d7fd0429940"

GitHub sha: 5a1990a9

This commit appears in #223 which was approved by blake. It was merged by blake.