Class: Tpaga::Swagger::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/tpaga/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/tpaga/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/tpaga/swagger/request.rb', line 8

def auth_names
  @auth_names
end

#bodyObject

Returns the value of attribute body.



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

def body
  @body
end

#form_paramsObject

Returns the value of attribute form_params.



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

def form_params
  @form_params
end

#formatObject

Returns the value of attribute format.



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

def format
  @format
end

#headersObject

Returns the value of attribute headers.



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

def headers
  @headers
end

#hostObject

Returns the value of attribute host.



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

def host
  @host
end

#http_methodObject

Returns the value of attribute http_method.



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

def http_method
  @http_method
end

#paramsObject

Returns the value of attribute params.



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

def params
  @params
end

#pathObject

Returns the value of attribute path.



8
9
10
# File 'lib/tpaga/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



260
261
262
263
264
265
266
# File 'lib/tpaga/swagger/request.rb', line 260

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



246
247
248
249
250
251
252
253
254
255
# File 'lib/tpaga/swagger/request.rb', line 246

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)



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

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)



233
234
235
236
237
238
239
240
241
# File 'lib/tpaga/swagger/request.rb', line 233

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_api_key_with_prefix(param_name) ⇒ Object

Get API key (with prefix if set).

Parameters:

  • param_name (String)

    the parameter name of API key auth



54
55
56
57
58
59
60
# File 'lib/tpaga/swagger/request.rb', line 54

def get_api_key_with_prefix(param_name)
  if Swagger.configuration.api_key_prefix[param_name].present?
    "#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}"
  else
    Swagger.configuration.api_key[param_name]
  end
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



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

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



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

def make
  #TODO use configuration setting to determine if debugging
  #logger = Logger.new STDOUT
  #logger.debug self.url

  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
    )

  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



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

def outgoing_body
  # http form
  if headers['Content-Type'] == 'application/x-www-form-urlencoded'
    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



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

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



202
203
204
# File 'lib/tpaga/swagger/request.rb', line 202

def response
  self.make
end

#response_code_prettyObject



206
207
208
209
# File 'lib/tpaga/swagger/request.rb', line 206

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

#response_headers_prettyObject



211
212
213
214
215
# File 'lib/tpaga/swagger/request.rb', line 211

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

def update_params_for_auth!
  (@auth_names || []).each do |auth_name|
    case auth_name
    when 'api_key'
      @headers ||= {}
      http_auth_header = 'Basic ' + ["#{Swagger.configuration.api_key}:"].pack('m').delete("\r\n")
      @headers['Authorization'] = http_auth_header
    
    end
  end
end

#url(options = {}) ⇒ Object

Construct a base URL



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

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

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

  u
end