Done with API client structure for Ruby client

This commit is contained in:
xhh 2015-07-22 15:37:29 +08:00
parent 4ecc757bea
commit 948cdb3a75
8 changed files with 298 additions and 345 deletions

View File

@ -18,8 +18,8 @@ module {{moduleName}}
{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}}
{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}]
def {{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
if @client.debugging
@client.logger.debug "Calling API: {{classname}}#{{nickname}} ..."
if @api_client.debugging
@api_client.logger.debug "Calling API: {{classname}}#{{nickname}} ..."
end
{{#allParams}}{{#required}}
# verify the required parameter '{{paramName}}' is set
@ -64,14 +64,14 @@ module {{moduleName}}
{{/bodyParam}}
auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]
{{#returnType}}response = Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
{{#returnType}}response = Request.new(@api_client, :{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('{{{returnType}}}')
if @client.debugging
@client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}"
if @api_client.debugging
@api_client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}"
end
result{{/returnType}}{{^returnType}}Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if @client.debugging
@client.logger.debug "API called: {{classname}}#{{nickname}}"
result{{/returnType}}{{^returnType}}Request.new(@api_client, :{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if @api_client.debugging
@api_client.logger.debug "API called: {{classname}}#{{nickname}}"
end
nil{{/returnType}}
end

View File

@ -3,75 +3,132 @@ require 'json'
module {{moduleName}}
class ApiClient
attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
#
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
attr_accessor :ssl_ca_cert
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debugging
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# A Swagger configuration object. Must act like a hash and return sensible
# values for all Swagger configuration options. See Swagger::Configuration.
attr_accessor :configuration
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
attr_accessor :resources
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Call this method to modify defaults in your initializers.
# Stores the HTTP response from the last API call using this API client.
attr_accessor :last_response
# The constructor accepts a optional block to configure the API client.
#
# @example
# Swagger.configure do |config|
# config.api_key['api_key'] = '1234567890abcdef' # api key authentication
# config.username = 'wordlover' # http basic authentication
# config.password = 'i<3words' # http basic authentication
# config.format = 'json' # optional, defaults to 'json'
# {{moduleName}}::ApiClient.new do |client|
# client.api_key['api_key'] = 'your key' # api key authentication
# client.username = 'your username' # username for http basic authentication
# client.password = 'your password' # password for http basic authentication
# client.format = 'json' # optional, defaults to 'json'
# end
#
def configure
yield(configuration) if block_given?
def initialize(&block)
@format = 'json'
@scheme = '{{scheme}}'
@host = '{{host}}'
@base_path = '{{contextPath}}'
@user_agent = "ruby-swagger-#{VERSION}"
@inject_format = false
@force_ending_format = false
self.logger = configuration.logger
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
# keys for API key authentication (param-name => api-key)
@api_key = {}
@api_key_prefix = {}
@verify_ssl = true
@debugging = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
configure(&block)
end
# Call this method to modify defaults in your initializers.
def configure
yield(self) if block_given?
# remove :// from scheme
configuration.scheme.sub!(/:\/\//, '')
@scheme.sub!(/:\/\//, '')
# remove http(s):// and anything after a slash
configuration.host.sub!(/https?:\/\//, '')
configuration.host = configuration.host.split('/').first
@host.sub!(/https?:\/\//, '')
@host = @host.split('/').first
# Add leading and trailing slashes to base_path
configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/')
configuration.base_path = "" if configuration.base_path == "/"
@base_path = "/#{@base_path}".gsub(/\/+/, '/')
@base_path = "" if @base_path == "/"
end
def authenticated?
!Swagger.configuration.auth_token.nil?
end
def de_authenticate
Swagger.configuration.auth_token = nil
end
def authenticate
return if Swagger.authenticated?
if Swagger.configuration.username.nil? || Swagger.configuration.password.nil?
raise ApiError, "Username and password are required to authenticate."
end
request = Swagger::Request.new(
:get,
"account/authenticate/{username}",
:params => {
:username => Swagger.configuration.username,
:password => Swagger.configuration.password
}
)
response_body = request.response.body
Swagger.configuration.auth_token = response_body['token']
end
def last_response
Thread.current[:swagger_last_response]
end
def last_response=(response)
Thread.current[:swagger_last_response] = response
def user_agent=(user_agent)
@user_agent = user_agent
@default_headers['User-Agent'] = @user_agent
end
end
end

View File

@ -0,0 +1,24 @@
module {{moduleName}}
class ApiError < StandardError
attr_reader :code, :response_headers, :response_body
# Usage examples:
# ApiError.new
# ApiError.new("message")
# ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
# ApiError.new(:code => 404, :message => "Not Found")
def initialize(arg = nil)
if arg.is_a? Hash
arg.each do |k, v|
if k.to_s == 'message'
super v
else
instance_variable_set "@#{k}", v
end
end
else
super arg
end
end
end
end

View File

@ -124,7 +124,7 @@ module {{moduleName}}
end
raw = Typhoeus::Request.new(self.url, request_options).run
@response = Response.new(raw)
@response = Response.new(@api_client, raw)
if @api_client.debugging
@api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n"

View File

@ -0,0 +1,155 @@
require 'json'
require 'date'
require 'tempfile'
module {{moduleName}}
class Response
attr_accessor :raw
def initialize(api_client, raw)
@api_client = api_client
@raw = raw
end
def code
raw.code
end
def status_message
raw.status_message
end
def body
raw.body
end
def success?
raw.success?
end
# Deserialize the raw response body to the given return type.
#
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(return_type)
return nil if body.nil? || body.empty?
# handle file downloading - save response body into a tmp file and return the File instance
return download_file if return_type == 'File'
# ensuring a default content type
content_type = raw.headers['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}"
end
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object, return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet
{{moduleName}}.const_get(return_type).new.tap do |model|
model.build_from_hash data
end
end
end
# Save response body into a file in (the defined) temporary folder, using the filename
# from the "Content-Disposition" header if provided, otherwise a random filename.
#
# @see Configuration#temp_folder_path
# @return [File] the file downloaded
def download_file
tmp_file = Tempfile.new '', @api_client.temp_folder_path
content_disposition = raw.headers['Content-Disposition']
if content_disposition
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
path = File.join File.dirname(tmp_file), filename
else
path = tmp_file.path
end
# close and delete temp file
tmp_file.close!
File.open(path, 'w') { |file| file.write(raw.body) }
@api_client.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards"
return File.new(path)
end
# `headers_hash` is a Typhoeus-specific extension of Hash,
# so simplify it back into a regular old Hash.
def headers
h = {}
raw.headers_hash.each {|k,v| h[k] = v }
h
end
# Extract the response format from the header hash
# e.g. {'Content-Type' => 'application/json'}
def format
headers['Content-Type'].split("/").last.downcase
end
def json?
format == 'json'
end
def xml?
format == 'xml'
end
def pretty_body
return unless body
if format == 'json'
JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
else
body
end
end
def pretty_headers
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end
end
end

View File

@ -1,26 +0,0 @@
module {{moduleName}}
module Swagger
class ApiError < StandardError
attr_reader :code, :response_headers, :response_body
# Usage examples:
# ApiError.new
# ApiError.new("message")
# ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
# ApiError.new(:code => 404, :message => "Not Found")
def initialize(arg = nil)
if arg.is_a? Hash
arg.each do |k, v|
if k.to_s == 'message'
super v
else
instance_variable_set "@#{k}", v
end
end
else
super arg
end
end
end
end
end

View File

@ -1,101 +0,0 @@
require 'logger'
module {{moduleName}}
module Swagger
class Configuration
attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
#
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
attr_accessor :ssl_ca_cert
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debug
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Defaults go in here..
def initialize
@format = 'json'
@scheme = '{{scheme}}'
@host = '{{host}}'
@base_path = '{{contextPath}}'
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = false
@force_ending_format = false
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
# keys for API key authentication (param-name => api-key)
@api_key = {}
@api_key_prefix = {}
@verify_ssl = true
@debug = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
end
end
end
end

View File

@ -1,156 +0,0 @@
module {{moduleName}}
module Swagger
class Response
require 'json'
require 'date'
require 'tempfile'
attr_accessor :raw
def initialize(raw)
self.raw = raw
end
def code
raw.code
end
def status_message
raw.status_message
end
def body
raw.body
end
def success?
raw.success?
end
# Deserialize the raw response body to the given return type.
#
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(return_type)
return nil if body.nil? || body.empty?
# handle file downloading - save response body into a tmp file and return the File instance
return download_file if return_type == 'File'
# ensuring a default content type
content_type = raw.headers['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}"
end
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object, return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet
{{moduleName}}.const_get(return_type).new.tap do |model|
model.build_from_hash data
end
end
end
# Save response body into a file in (the defined) temporary folder, using the filename
# from the "Content-Disposition" header if provided, otherwise a random filename.
#
# @see Configuration#temp_folder_path
# @return [File] the file downloaded
def download_file
tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path
content_disposition = raw.headers['Content-Disposition']
if content_disposition
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
path = File.join File.dirname(tmp_file), filename
else
path = tmp_file.path
end
# close and delete temp file
tmp_file.close!
File.open(path, 'w') { |file| file.write(raw.body) }
Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards"
return File.new(path)
end
# `headers_hash` is a Typhoeus-specific extension of Hash,
# so simplify it back into a regular old Hash.
def headers
h = {}
raw.headers_hash.each {|k,v| h[k] = v }
h
end
# Extract the response format from the header hash
# e.g. {'Content-Type' => 'application/json'}
def format
headers['Content-Type'].split("/").last.downcase
end
def json?
format == 'json'
end
def xml?
format == 'xml'
end
def pretty_body
return unless body
if format == 'json'
JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
else
body
end
end
def pretty_headers
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end
end
end
end