rollback ruby swagger template

This commit is contained in:
wing328 2015-06-09 12:26:02 +08:00
parent 0dd8670724
commit d5cbbae182
4 changed files with 317 additions and 317 deletions

View File

@ -1,29 +1,29 @@
module {{moduleName}} module {{moduleName}}
module Swagger module Swagger
class Configuration class Configuration
attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl
# Defaults go in here.. # Defaults go in here..
def initialize def initialize
@format = 'json' @format = 'json'
@scheme = '{{scheme}}' @scheme = '{{scheme}}'
@host = '{{host}}' @host = '{{host}}'
@base_path = '{{contextPath}}' @base_path = '{{contextPath}}'
@user_agent = "ruby-swagger-#{Swagger::VERSION}" @user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = false @inject_format = false
@force_ending_format = false @force_ending_format = false
@camelize_params = true @camelize_params = true
# keys for API key authentication (param-name => api-key) # keys for API key authentication (param-name => api-key)
@api_key = {} @api_key = {}
# api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix) # api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix)
@api_key_prefix = {} @api_key_prefix = {}
# whether to verify SSL certificate, default to true # whether to verify SSL certificate, default to true
# Note: do NOT set it to false in production code, otherwise you would # Note: do NOT set it to false in production code, otherwise you would
# face multiple types of cryptographic attacks # face multiple types of cryptographic attacks
@verify_ssl = true @verify_ssl = true
end end
end end
end end
end end

View File

@ -1,272 +1,272 @@
module {{moduleName}} module {{moduleName}}
module Swagger module Swagger
class Request class Request
require 'uri' require 'uri'
require 'addressable/uri' require 'addressable/uri'
require 'typhoeus' require 'typhoeus'
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names
# All requests must have an HTTP method and a path # All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host # Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes={}) def initialize(http_method, path, attributes={})
attributes[:format] ||= Swagger.configuration.format attributes[:format] ||= Swagger.configuration.format
attributes[:params] ||= {} attributes[:params] ||= {}
# Set default headers # Set default headers
default_headers = { default_headers = {
'Content-Type' => "application/#{attributes[:format].downcase}", 'Content-Type' => "application/#{attributes[:format].downcase}",
'User-Agent' => Swagger.configuration.user_agent 'User-Agent' => Swagger.configuration.user_agent
} }
# Merge argument headers into defaults # Merge argument headers into defaults
attributes[:headers] = default_headers.merge(attributes[:headers] || {}) attributes[:headers] = default_headers.merge(attributes[:headers] || {})
# Stick in the auth token if there is one # Stick in the auth token if there is one
if Swagger.authenticated? if Swagger.authenticated?
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
end end
self.http_method = http_method.to_sym self.http_method = http_method.to_sym
self.path = path self.path = path
attributes.each do |name, value| attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value) send("#{name.to_s.underscore.to_sym}=", value)
end end
update_params_for_auth! update_params_for_auth!
end end
# Update hearder and query params based on authentication settings. # Update hearder and query params based on authentication settings.
def update_params_for_auth! def update_params_for_auth!
(@auth_names || []).each do |auth_name| (@auth_names || []).each do |auth_name|
case auth_name case auth_name
{{#authMethods}}when '{{name}}' {{#authMethods}}when '{{name}}'
{{#isApiKey}}{{#isKeyInHeader}}@headers ||= {} {{#isApiKey}}{{#isKeyInHeader}}@headers ||= {}
@headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {} @headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {}
@params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {} @params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {}
http_auth_header = 'Basic ' + ["#{Swagger.configuration.username}:#{Swagger.configuration.password}"].pack('m').delete("\r\n") http_auth_header = 'Basic ' + ["#{Swagger.configuration.username}:#{Swagger.configuration.password}"].pack('m').delete("\r\n")
@headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} @headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}}
{{/authMethods}} {{/authMethods}}
end end
end end
end end
# Get API key (with prefix if set). # Get API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth # @param [String] param_name the parameter name of API key auth
def get_api_key_with_prefix(param_name) def get_api_key_with_prefix(param_name)
if Swagger.configuration.api_key_prefix[param_name].present? if Swagger.configuration.api_key_prefix[param_name].present?
"#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}" "#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}"
else else
Swagger.configuration.api_key[param_name] Swagger.configuration.api_key[param_name]
end end
end end
# Construct a base URL # Construct a base URL
def url(options = {}) def url(options = {})
u = Addressable::URI.new( u = Addressable::URI.new(
:scheme => Swagger.configuration.scheme, :scheme => Swagger.configuration.scheme,
:host => Swagger.configuration.host, :host => Swagger.configuration.host,
:path => self.interpreted_path, :path => self.interpreted_path,
:query => self.query_string.sub(/\?/, '') :query => self.query_string.sub(/\?/, '')
).to_s ).to_s
# Drop trailing question mark, if present # Drop trailing question mark, if present
u.sub! /\?$/, '' u.sub! /\?$/, ''
u u
end end
# Iterate over the params hash, injecting any path values into the path string # Iterate over the params hash, injecting any path values into the path string
# e.g. /word.{format}/{word}/entries => /word.json/cat/entries # e.g. /word.{format}/{word}/entries => /word.json/cat/entries
def interpreted_path def interpreted_path
p = self.path.dup p = self.path.dup
# Stick a .{format} placeholder into the path if there isn't # Stick a .{format} placeholder into the path if there isn't
# one already or an actual format like json or xml # one already or an actual format like json or xml
# e.g. /words/blah => /words.{format}/blah # e.g. /words/blah => /words.{format}/blah
if Swagger.configuration.inject_format if Swagger.configuration.inject_format
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
p = p.sub(/^(\/?\w+)/, "\\1.#{format}") p = p.sub(/^(\/?\w+)/, "\\1.#{format}")
end end
end end
# Stick a .{format} placeholder on the end of the path if there isn't # Stick a .{format} placeholder on the end of the path if there isn't
# one already or an actual format like json or xml # one already or an actual format like json or xml
# e.g. /words/blah => /words/blah.{format} # e.g. /words/blah => /words/blah.{format}
if Swagger.configuration.force_ending_format if Swagger.configuration.force_ending_format
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
p = "#{p}.#{format}" p = "#{p}.#{format}"
end end
end end
p = p.sub("{format}", self.format.to_s) p = p.sub("{format}", self.format.to_s)
URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
end end
# Massage the request body into a state of readiness # Massage the request body into a state of readiness
# If body is a hash, camelize all keys then convert to a json string # If body is a hash, camelize all keys then convert to a json string
def body=(value) def body=(value)
if value.is_a?(Hash) if value.is_a?(Hash)
value = value.inject({}) do |memo, (k,v)| value = value.inject({}) do |memo, (k,v)|
memo[k.to_s.camelize(:lower).to_sym] = v memo[k.to_s.camelize(:lower).to_sym] = v
memo memo
end end
end end
@body = value @body = value
end end
# If body is an object, JSONify it before making the actual request. # If body is an object, JSONify it before making the actual request.
# For form parameters, remove empty value # For form parameters, remove empty value
def outgoing_body def outgoing_body
# http form # http form
if headers['Content-Type'] == 'application/x-www-form-urlencoded' if headers['Content-Type'] == 'application/x-www-form-urlencoded'
data = form_params.dup data = form_params.dup
data.each do |key, value| data.each do |key, value|
data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter
end end
data data
elsif @body # http body is JSON elsif @body # http body is JSON
@body.is_a?(String) ? @body : @body.to_json @body.is_a?(String) ? @body : @body.to_json
else else
nil nil
end end
end end
# Construct a query string from the query-string-type params # Construct a query string from the query-string-type params
def query_string def query_string
# Iterate over all params, # Iterate over all params,
# .. removing the ones that are part of the path itself. # .. removing the ones that are part of the path itself.
# .. stringifying values so Addressable doesn't blow up. # .. stringifying values so Addressable doesn't blow up.
query_values = {} query_values = {}
self.params.each_pair do |key, value| self.params.each_pair do |key, value|
next if self.path.include? "{#{key}}" # skip path params next if self.path.include? "{#{key}}" # skip path params
next if value.blank? && value.class != FalseClass # skip empties next if value.blank? && value.class != FalseClass # skip empties
if Swagger.configuration.camelize_params if Swagger.configuration.camelize_params
key = key.to_s.camelize(:lower).to_sym key = key.to_s.camelize(:lower).to_sym
end end
query_values[key] = value.to_s query_values[key] = value.to_s
end end
# We don't want to end up with '?' as our query string # We don't want to end up with '?' as our query string
# if there aren't really any params # if there aren't really any params
return "" if query_values.blank? return "" if query_values.blank?
# Addressable requires query_values to be set after initialization.. # Addressable requires query_values to be set after initialization..
qs = Addressable::URI.new qs = Addressable::URI.new
qs.query_values = query_values qs.query_values = query_values
qs.to_s qs.to_s
end end
def make def make
#TODO use configuration setting to determine if debugging #TODO use configuration setting to determine if debugging
#logger = Logger.new STDOUT #logger = Logger.new STDOUT
#logger.debug self.url #logger.debug self.url
request_options = { request_options = {
:ssl_verifypeer => Swagger.configuration.verify_ssl, :ssl_verifypeer => Swagger.configuration.verify_ssl,
:headers => self.headers.stringify_keys :headers => self.headers.stringify_keys
} }
response = case self.http_method.to_sym response = case self.http_method.to_sym
when :get,:GET when :get,:GET
Typhoeus::Request.get( Typhoeus::Request.get(
self.url, self.url,
request_options request_options
) )
when :post,:POST when :post,:POST
Typhoeus::Request.post( Typhoeus::Request.post(
self.url, self.url,
request_options.merge(:body => self.outgoing_body) request_options.merge(:body => self.outgoing_body)
) )
when :patch,:PATCH when :patch,:PATCH
Typhoeus::Request.patch( Typhoeus::Request.patch(
self.url, self.url,
request_options.merge(:body => self.outgoing_body) request_options.merge(:body => self.outgoing_body)
) )
when :put,:PUT when :put,:PUT
Typhoeus::Request.put( Typhoeus::Request.put(
self.url, self.url,
request_options.merge(:body => self.outgoing_body) request_options.merge(:body => self.outgoing_body)
) )
when :delete,:DELETE when :delete,:DELETE
Typhoeus::Request.delete( Typhoeus::Request.delete(
self.url, self.url,
request_options.merge(:body => self.outgoing_body) request_options.merge(:body => self.outgoing_body)
) )
end end
Response.new(response) Response.new(response)
end end
def response def response
self.make self.make
end end
def response_code_pretty def response_code_pretty
return unless @response.present? return unless @response.present?
@response.code.to_s @response.code.to_s
end end
def response_headers_pretty def response_headers_pretty
return unless @response.present? return unless @response.present?
# JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient # JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus @response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end end
# return 'Accept' based on an array of accept provided # return 'Accept' based on an array of accept provided
# @param [Array] header_accept_array Array fo 'Accept' # @param [Array] header_accept_array Array fo 'Accept'
# @return String Accept (e.g. application/json) # @return String Accept (e.g. application/json)
def self.select_header_accept header_accept_array def self.select_header_accept header_accept_array
if header_accept_array.empty? if header_accept_array.empty?
return return
elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 }
'application/json' # look for json data by default 'application/json' # look for json data by default
else else
header_accept_array.join(',') header_accept_array.join(',')
end end
end end
# return the content type based on an array of content-type provided # return the content type based on an array of content-type provided
# @param [Array] content_type_array Array fo content-type # @param [Array] content_type_array Array fo content-type
# @return String Content-Type (e.g. application/json) # @return String Content-Type (e.g. application/json)
def self.select_header_content_type content_type_array def self.select_header_content_type content_type_array
if content_type_array.empty? if content_type_array.empty?
'application/json' # use application/json by default 'application/json' # use application/json by default
elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 }
'application/json' # use application/json if it's included 'application/json' # use application/json if it's included
else else
content_type_array[0]; # otherwise, use the first one content_type_array[0]; # otherwise, use the first one
end end
end end
# static method to convert object (array, hash, object, etc) to JSON string # static method to convert object (array, hash, object, etc) to JSON string
# @param model object to be converted into JSON string # @param model object to be converted into JSON string
# @return string JSON string representation of the object # @return string JSON string representation of the object
def self.object_to_http_body model def self.object_to_http_body model
return if model.nil? return if model.nil?
_body = nil _body = nil
if model.is_a?(Array) if model.is_a?(Array)
_body = model.map{|m| object_to_hash(m) } _body = model.map{|m| object_to_hash(m) }
else else
_body = object_to_hash(model) _body = object_to_hash(model)
end end
_body.to_json _body.to_json
end end
# static method to convert object(non-array) to hash # static method to convert object(non-array) to hash
# @param obj object to be converted into JSON string # @param obj object to be converted into JSON string
# @return string JSON string representation of the object # @return string JSON string representation of the object
def self.object_to_hash obj def self.object_to_hash obj
if obj.respond_to?(:to_hash) if obj.respond_to?(:to_hash)
obj.to_hash obj.to_hash
else else
obj obj
end end
end end
end end
end end
end end

View File

@ -1,70 +1,70 @@
module {{moduleName}} module {{moduleName}}
module Swagger module Swagger
class Response class Response
require 'json' require 'json'
attr_accessor :raw attr_accessor :raw
def initialize(raw) def initialize(raw)
self.raw = raw self.raw = raw
case self.code case self.code
when 500..510 then raise(ServerError, self.error_message) when 500..510 then raise(ServerError, self.error_message)
when 299..426 then raise(ClientError, self.error_message) when 299..426 then raise(ClientError, self.error_message)
end end
end end
def code def code
raw.code raw.code
end end
# Account for error messages that take different forms... # Account for error messages that take different forms...
def error_message def error_message
body['message'] body['message']
rescue rescue
body body
end end
# If body is JSON, parse it # If body is JSON, parse it
# Otherwise return raw string # Otherwise return raw string
def body def body
JSON.parse(raw.body, :symbolize_names => true) JSON.parse(raw.body, :symbolize_names => true)
rescue rescue
raw.body raw.body
end end
# `headers_hash` is a Typhoeus-specific extension of Hash, # `headers_hash` is a Typhoeus-specific extension of Hash,
# so simplify it back into a regular old Hash. # so simplify it back into a regular old Hash.
def headers def headers
h = {} h = {}
raw.headers_hash.each {|k,v| h[k] = v } raw.headers_hash.each {|k,v| h[k] = v }
h h
end end
# Extract the response format from the header hash # Extract the response format from the header hash
# e.g. {'Content-Type' => 'application/json'} # e.g. {'Content-Type' => 'application/json'}
def format def format
headers['Content-Type'].split("/").last.downcase headers['Content-Type'].split("/").last.downcase
end end
def json? def json?
format == 'json' format == 'json'
end end
def xml? def xml?
format == 'xml' format == 'xml'
end end
def pretty_body def pretty_body
return unless body.present? return unless body.present?
case format case format
when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>') when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
end end
end end
def pretty_headers def pretty_headers
JSON.pretty_generate(headers).gsub(/\n/, '<br/>') JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end end
end end
end end
end end

View File

@ -1,5 +1,5 @@
module {{moduleName}} module {{moduleName}}
module Swagger module Swagger
VERSION = "{{appVersion}}" VERSION = "{{appVersion}}"
end end
end end