Class: PlateApi::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/plate_api/request.rb

Constant Summary collapse

DefaultApiBaseEndpoint =
"https://www.startwithplate.com/api/v2"
HttpAdapter =
Faraday.default_adapter

Instance Method Summary collapse

Constructor Details

#initialize(public_key, secret, method, path, custom_server = nil) ⇒ Request

Returns a new instance of Request.



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/plate_api/request.rb', line 14

def initialize(public_key, secret, method, path, custom_server = nil)
  base_api_endpoint = custom_server || DefaultApiBaseEndpoint

  @connection = ::Faraday.new(url: base_api_endpoint, request: { timeout: 900 }) do |faraday|
    extra_builder_options(faraday)
    faraday.adapter HttpAdapter
  end

  @public_key = public_key
  @secret = secret
  @method = method
  @path = strip_path(path)
end

Instance Method Details

#calculate_signatureObject



48
49
50
51
52
53
54
55
56
# File 'lib/plate_api/request.rb', line 48

def calculate_signature
  string_to_sign = "#{@method}\n" +
                   "#{@connection.host}\n" +
                   "#{@connection.path_prefix}/#{@path}\n" +
                   "#{url_parameters}\n" +
                   request_date.to_s
  signature = Base64.strict_encode64(OpenSSL::HMAC.digest("SHA512", @secret, string_to_sign))
  "hmac #{@public_key}:#{signature}"
end

#execute(response_type = :raw) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/plate_api/request.rb', line 28

def execute(response_type = :raw)
  response = @connection.send(@method.downcase) do |request|
    request.url url_path
    request.headers["Date"] = request_date
    request.headers["Authorization"] = calculate_signature
    extra_request_options(request)
  end

  case response_type
  when :raw
    response.body
  when :json
    JSON.parse(response.body)
  end
end

#request_dateObject



44
45
46
# File 'lib/plate_api/request.rb', line 44

def request_date
  @date ||= Time.now.httpdate
end