Class: Idlc::AWSRestClient

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/iapi-idlc-sdk-core/restclient.rb

Instance Method Summary collapse

Methods included from Helpers

debug, err, msg, stderr, stdout, system_command

Constructor Details

#initialize(credentials = { access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], session_token: ENV['AWS_SESSION_TOKEN'] }, region = ) ⇒ AWSRestClient

Returns a new instance of AWSRestClient.



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/iapi-idlc-sdk-core/restclient.rb', line 58

def initialize(credentials=  {
      access_key_id: ENV['AWS_ACCESS_KEY_ID'],
      secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
      session_token: ENV['AWS_SESSION_TOKEN']
    },
    region=ENV['AWS_REGION']
  )
  @service_name = 'execute-api'
  @credentials = credentials
  @region = region
  @backend_services = Idlc::SERVICES[region]
end

Instance Method Details

#fetch(request) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/iapi-idlc-sdk-core/restclient.rb', line 71

def fetch(request)
  request = JSON.parse(request)

  endpoint = 'https://' + @backend_services[request['service']]['endpoint'] + '/' + @backend_services[request['service']]['stage']

  body = ''
  body = request['body'].to_json if request['body']

  retries = 0
  max_retries = 5
  sleep_time = 5
  exp_backoff = 2
  result = nil

  loop do
    begin
      resp = send_signed_request(
        request['method'],
        "#{endpoint.strip}#{request['path']}",
        body
      )

      result = JSON.parse(resp.body)
      message = "status: #{resp.code}, response: #{result}"
      raise message unless resp.code == '200'
      break
    rescue Exception => e
      break if retries >= max_retries
      retries += 1
      msg("RequestFailed: #{e} - Waiting #{sleep_time}s then retrying... (#{retries} of #{max_retries})")


      sleep sleep_time
      sleep_time *= exp_backoff # use an exponential backoff when retrying requests
    end
  end

  # if request has 'outfile' param, write response body to file
  to_file(result, request['outfile']) if request['outfile']

  # return response body obj
  result
end

#to_file(obj, filename) ⇒ Object



115
116
117
118
119
# File 'lib/iapi-idlc-sdk-core/restclient.rb', line 115

def to_file(obj, filename)
  File.open(filename, 'w') do |f|
    f.write(obj.to_json)
  end
end