Sha256: caf34679adaeab1bd8b6d810aea3ab516106ed02d6748e662f1234c193bf6fb9

Contents?: true

Size: 1.46 KB

Versions: 6

Compression:

Stored size: 1.46 KB

Contents

module Senec
  module Cloud
    class Connection
      def initialize(username:, password:, token: nil)
        @username = username
        @password = password
        @token = token
      end

      attr_reader :username, :password

      def authenticated?
        !token.nil?
      end

      def systems
        get('/v1/senec/systems')
      end

      def default_system_id
        raise Error.new('No systems found!', :not_found) if systems.nil?

        systems[0]['id']
      end

      def get(path, params: nil)
        return_body do
          connection.get(path, params, { authorization: token })
        end
      end

      def post(path, data)
        return_body do
          connection.post(path, data)
        end
      end

      def token
        @token ||= login['token']
      end

      private

      def login
        post('/v1/senec/login', { username:, password: })
      end

      def connection
        @connection ||=
          Faraday.new(url: 'https://app-gateway.prod.senec.dev') do |f|
            f.request :json
            f.response :json

            f.adapter :net_http_persistent, pool_size: 5 do |http|
              # :nocov:
              http.idle_timeout = 120
              # :nocov:
            end
          end
      end

      def return_body(&)
        response = yield

        unless response.success?
          raise Error.new("Error #{response.status}", response.status)
        end

        response.body
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
senec-0.18.0 lib/senec/cloud/connection.rb
senec-0.17.2 lib/senec/cloud/connection.rb
senec-0.17.1 lib/senec/cloud/connection.rb
senec-0.17.0 lib/senec/cloud/connection.rb
senec-0.16.0 lib/senec/cloud/connection.rb
senec-0.15.0 lib/senec/cloud/connection.rb