Class: TranslationApiClient::Swagger::Request

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(http_method, path, attributes = {}) ⇒ Request

All requests must have an HTTP method and a path Optionals parameters are :params, :headers, :body, :format, :host



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/translationApi_client/swagger/request.rb', line 12

def initialize(http_method, path, attributes={})
  attributes[:format] ||= Swagger.configuration.format
  attributes[:params] ||= {}

  # Set default headers
  default_headers = {
      'Content-Type' => "application/#{attributes[:format].downcase}",
      'User-Agent' => Swagger.configuration.user_agent
  }

  # Merge argument headers into defaults
  attributes[:headers] = default_headers.merge(attributes[:headers] || {})

  # Stick in the auth token if there is one
  if Swagger.authenticated?
    attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
  end

  self.http_method = http_method.to_sym
  self.path = path
  attributes.each do |name, value|
    send("#{name.to_s.underscore.to_sym}=", value)
  end

  update_params_for_auth!
end

Instance Attribute Details

#auth_namesObject

Returns the value of attribute auth_names.



8
9
10
# File 'lib/translationApi_client/swagger/request.rb', line 8

def auth_names
  @auth_names
end

#bodyObject

Returns the value of attribute body.



8
9
10
# File 'lib/translationApi_client/swagger/request.rb', line 8

def body
  @body
end

#form_paramsObject

Returns the value of attribute form_params.



8
9
10
# File 'lib/translationApi_client/swagger/request.rb', line 8

def form_params
  @form_params
end

#formatObject

Returns the value of attribute format.



8
9
10
# File 'lib/translationApi_client/swagger/request.rb', line 8

def format
  @format
end

#headersObject

Returns the value of attribute headers.



8
9
10
# File 'lib/translationApi_client/swagger/request.rb', line 8

def headers
  @headers
end

#hostObject

Returns the value of attribute host.



8
9
10
# File 'lib/translationApi_client/swagger/request.rb', line 8

def host
  @host
end

#http_methodObject

Returns the value of attribute http_method.



8
9
10
# File 'lib/translationApi_client/swagger/request.rb', line 8

def http_method
  @http_method
end

#paramsObject

Returns the value of attribute params.



8
9
10
# File 'lib/translationApi_client/swagger/request.rb', line 8

def params
  @params
end

#pathObject

Returns the value of attribute path.



8
9
10
# File 'lib/translationApi_client/swagger/request.rb', line 8

def path
  @path
end

Class Method Details

.object_to_hash(obj) ⇒ Object

static method to convert object(non-array) to hash

Parameters:

  • obj

    object to be converted into JSON string

Returns:

  • string JSON string representation of the object



262
263
264
265
266
267
268
# File 'lib/translationApi_client/swagger/request.rb', line 262

def self.object_to_hash obj
  if obj.respond_to?(:to_hash)
    obj.to_hash
  else
    obj
  end
end

.object_to_http_body(model) ⇒ Object

static method to convert object (array, hash, object, etc) to JSON string

Parameters:

  • model

    object to be converted into JSON string

Returns:

  • string JSON string representation of the object



248
249
250
251
252
253
254
255
256
257
# File 'lib/translationApi_client/swagger/request.rb', line 248

def self.object_to_http_body model
  return if model.nil?
  _body = nil
  if model.is_a?(Array)
    _body = model.map{|m| object_to_hash(m) }
  else
    _body = object_to_hash(model)
  end
  _body.to_json
end

.select_header_accept(header_accept_array) ⇒ Object

return ‘Accept’ based on an array of accept provided

Parameters:

  • header_accept_array (Array)

    Array fo ‘Accept’

Returns:

  • String Accept (e.g. application/json)



221
222
223
224
225
226
227
228
229
# File 'lib/translationApi_client/swagger/request.rb', line 221

def self.select_header_accept header_accept_array
  if header_accept_array.empty?
    return
  elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 }
    'application/json' # look for json data by default
  else
    header_accept_array.join(',')
  end
end

.select_header_content_type(content_type_array) ⇒ Object

return the content type based on an array of content-type provided

Parameters:

  • content_type_array (Array)

    Array fo content-type

Returns:

  • String Content-Type (e.g. application/json)



234
235
236
237
238
239
240
241
242
243
# File 'lib/translationApi_client/swagger/request.rb', line 234

def self.select_header_content_type content_type_array
  if content_type_array.empty?
    'application/json' # use application/json by default

  elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 }
    'application/json' # use application/json if it's included
  else
    content_type_array[0]; # otherwise, use the first one
  end
end

Instance Method Details

#get_key_with_prefix(param_name) ⇒ Object

Get API key (with prefix if set).

Parameters:

  • param_name (String)

    the parameter name of API key auth



56
57
58
# File 'lib/translationApi_client/swagger/request.rb', line 56

def get_key_with_prefix(param_name)
  Swagger.configuration.key
end

#interpreted_pathObject

Iterate over the params hash, injecting any path values into the path string e.g. /word.#format/word/entries => /word.json/cat/entries



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
# File 'lib/translationApi_client/swagger/request.rb', line 78

def interpreted_path
  p = self.path.dup

  # Stick a .{format} placeholder into the path if there isn't
  # one already or an actual format like json or xml
  # e.g. /words/blah => /words.{format}/blah
  if Swagger.configuration.inject_format
    unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
      p = p.sub(/^(\/?\w+)/, "\\1.#{format}")
    end
  end

  # Stick a .{format} placeholder on the end of the path if there isn't
  # one already or an actual format like json or xml
  # e.g. /words/blah => /words/blah.{format}
  if Swagger.configuration.force_ending_format
    unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
      p = "#{p}.#{format}"
    end
  end

  p = p.sub("{format}", self.format.to_s)

  URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
end

#makeObject



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/translationApi_client/swagger/request.rb', line 158

def make
  #TODO use configuration setting to determine if debugging
  #logger = Logger.new STDOUT
  #logger.debug self.url
  if self.outgoing_body.nil? || self.outgoing_body.empty?
    self.headers['Content-Type'] = 'application/json'
  end
  request_options = {
      :ssl_verifypeer => Swagger.configuration.verify_ssl,
      :headers => self.headers.stringify_keys
  }
  response = case self.http_method.to_sym
               when :get,:GET
                 Typhoeus::Request.get(
                     self.url,
                     #request_options,
                     request_options.merge(:body => self.outgoing_body)
                 )
               when :post,:POST
                 Typhoeus::Request.post(
                     self.url,
                     request_options.merge(:body => self.outgoing_body)
                 )

               when :patch,:PATCH
                 Typhoeus::Request.patch(
                     self.url,
                     request_options.merge(:body => self.outgoing_body)
                 )

               when :put,:PUT
                 Typhoeus::Request.put(
                     self.url,
                     request_options.merge(:body => self.outgoing_body)
                 )

               when :delete,:DELETE
                 Typhoeus::Request.delete(
                     self.url,
                     request_options.merge(:body => self.outgoing_body)
                 )
             end
  Response.new(response)
end

#outgoing_bodyObject

If body is an object, JSONify it before making the actual request. For form parameters, remove empty value



118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/translationApi_client/swagger/request.rb', line 118

def outgoing_body
  # http form
  if headers['Content-Type'] == 'application/x-www-form-urlencoded' || headers['Content-Type'] == 'multipart/form-data'
    data = form_params.dup
    data.each do |key, value|
      data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter
    end
    data
  elsif @body # http body is JSON
    @body.is_a?(String) ? @body : @body.to_json
  else
    nil
  end
end

#query_stringObject

Construct a query string from the query-string-type params



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/translationApi_client/swagger/request.rb', line 134

def query_string
  # Iterate over all params,
  # .. removing the ones that are part of the path itself.
  # .. stringifying values so Addressable doesn't blow up.
  query_values = {}
  self.params.each_pair do |key, value|
    next if self.path.include? "{#{key}}"                                   # skip path params
    next if value.blank? && value.class != FalseClass                       # skip empties
    if Swagger.configuration.camelize_params
      key = key.to_s.camelize(:lower).to_sym
    end
    query_values[key] = value.to_s
  end

  # We don't want to end up with '?' as our query string
  # if there aren't really any params
  return "" if query_values.blank?

  # Addressable requires query_values to be set after initialization..
  qs = Addressable::URI.new
  qs.query_values = query_values
  qs.to_s
end

#responseObject



203
204
205
# File 'lib/translationApi_client/swagger/request.rb', line 203

def response
  self.make
end

#response_code_prettyObject



207
208
209
210
# File 'lib/translationApi_client/swagger/request.rb', line 207

def response_code_pretty
  return unless @response.present?
  @response.code.to_s
end

#response_headers_prettyObject



212
213
214
215
216
# File 'lib/translationApi_client/swagger/request.rb', line 212

def response_headers_pretty
  return unless @response.present?
  # JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
  @response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end

#update_params_for_auth!Object

Update hearder and query params based on authentication settings.



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/translationApi_client/swagger/request.rb', line 40

def update_params_for_auth!
  (@auth_names || []).each do |auth_name|
    case auth_name
      when 'apiKey'
        @params ||= {}
        @params['key'] = get_key_with_prefix('key')
      when 'accessToken'
        @headers ||= {}
        @headers['Authorization'] = get_key_with_prefix('Authorization')

    end
  end
end

#url(options = {}) ⇒ Object

Construct a base URL



61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/translationApi_client/swagger/request.rb', line 61

def url(options = {})
  u = Addressable::URI.new(
      :scheme => Swagger.configuration.scheme,
      :host => Swagger.configuration.host,
      :path => self.interpreted_path,
      :query => self.query_string.sub(/\?/, '')
  ).to_s
  puts ' url'

  puts u
  # Drop trailing question mark, if present
  u.sub! /\?$/, ''
  u
end