Completed
Pull Request — master (#17)
by
unknown
01:55
created

BaseRequest.client()   A

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
1
require 'json'
2
require 'net/http'
3
require 'net/https'
4
require 'uri'
5
6
module WePay
7
  module BaseRequest
8
9
    attr_reader :client_id,
10
                :client_secret,
11
                :api_version,
12
                :path,
13
                :access_token,
14
                :params
15
16
    def initialize(client_id, client_secret, api_version, path, access_token, params)
17
      @client_id     = client_id
18
      @client_secret = client_secret
19
      @api_version   = api_version
20
      @path          = path
21
      @access_token  = access_token
22
      @params        = params
23
    end
24
25
    def response
26
      JSON.parse(raw_response.body)
27
    end
28
29
    private
30
31
    def raw_response
32
      @raw_response ||= client.start do |c|
33
        c.request(request)
34
      end
35
    end
36
37
    def request
38
      @request ||= Net::HTTP::Post.new(uri.path, default_headers).tap do |r|
39
        if params.any?
40
          r.body = params.to_json
41
        end
42
43
        if access_token
44
          r.add_field('Authorization', "Bearer #{access_token}")
45
        end
46
47
        if api_version
48
          r.add_field('Api-Version', @api_version)
49
        end
50
      end
51
    end
52
53
    def client
54
      @client ||= Net::HTTP.new(uri.host, uri.port).tap do |c|
55
        c.read_timeout = 30
56
        c.use_ssl      = true
57
      end
58
    end
59
60
    def uri
61
      @uri ||= URI.join(api_endpoint, normalized_path)
62
    end
63
64
    def normalized_path
65
      return path if path.start_with?('/')
66
67
      path.prepend('/')
68
    end
69
70
    def default_headers
71
      {
72
        'Content-Type' => 'application/json',
73
        'User-Agent'   => 'WePay Ruby SDK'
74
      }
75
    end
76
  end
77
end
78