[crystal] Fix some issues in crystal client templates (#10629)

* Fix some issues in crystal client templates using google drive v3 oas3 api spec

* update crystal petstore sample code

* Address PR comments

Raises on unsupported feature
clean up extra new lines in partial_model_enum_class.mustache

* Use size instead of length

length is undefined for String or Array

* Fix typo

* Use default value instead of nil

* remove unused template file

* Use ::File instead of File as file type to avoid conflicts

The spec could also have a File model

* support file upload in multipart/form-data post body

* Revert breaking changes in api template

* Use double quotes to quote string values

single quotes are used for single char in crystal

* Update api_client to use global ::File and update petstore samples

* JSON Annotation Field key's value should be double quoted

* Handle nil values for form_params

* Remove default values from method definitions due to grammar error

* Fix integration tests
This commit is contained in:
cyangle 2021-10-22 22:34:08 -05:00 committed by GitHub
parent 885a813f86
commit 27459b5003
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 110 additions and 723 deletions

View File

@ -153,7 +153,7 @@ public class CrystalClientCodegen extends DefaultCodegen {
languageSpecificPrimitives.add("Time"); languageSpecificPrimitives.add("Time");
languageSpecificPrimitives.add("Array"); languageSpecificPrimitives.add("Array");
languageSpecificPrimitives.add("Hash"); languageSpecificPrimitives.add("Hash");
languageSpecificPrimitives.add("File"); languageSpecificPrimitives.add("::File");
languageSpecificPrimitives.add("Object"); languageSpecificPrimitives.add("Object");
typeMapping.clear(); typeMapping.clear();
@ -174,7 +174,7 @@ public class CrystalClientCodegen extends DefaultCodegen {
typeMapping.put("set", "Set"); typeMapping.put("set", "Set");
typeMapping.put("map", "Hash"); typeMapping.put("map", "Hash");
typeMapping.put("object", "Object"); typeMapping.put("object", "Object");
typeMapping.put("file", "File"); typeMapping.put("file", "::File");
typeMapping.put("binary", "String"); typeMapping.put("binary", "String");
typeMapping.put("ByteArray", "String"); typeMapping.put("ByteArray", "String");
typeMapping.put("UUID", "String"); typeMapping.put("UUID", "String");
@ -802,7 +802,7 @@ public class CrystalClientCodegen extends DefaultCodegen {
} else if (p.getDefault() instanceof java.time.OffsetDateTime) { } else if (p.getDefault() instanceof java.time.OffsetDateTime) {
return "Time.parse(\"" + String.format(Locale.ROOT, ((java.time.OffsetDateTime) p.getDefault()).atZoneSameInstant(ZoneId.systemDefault()).toString(), "") + "\")"; return "Time.parse(\"" + String.format(Locale.ROOT, ((java.time.OffsetDateTime) p.getDefault()).atZoneSameInstant(ZoneId.systemDefault()).toString(), "") + "\")";
} else { } else {
return "'" + escapeText((String) p.getDefault()) + "'"; return "\"" + escapeText((String) p.getDefault()) + "\"";
} }
} }
} }

View File

@ -80,13 +80,13 @@ module {{moduleName}}
{{/required}} {{/required}}
{{#hasValidation}} {{#hasValidation}}
{{#maxLength}} {{#maxLength}}
if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.to_s.length > {{{maxLength}}} if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.to_s.size > {{{maxLength}}}
raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, the character length must be smaller than or equal to {{{maxLength}}}.") raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, the character length must be smaller than or equal to {{{maxLength}}}.")
end end
{{/maxLength}} {{/maxLength}}
{{#minLength}} {{#minLength}}
if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.to_s.length < {{{minLength}}} if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.to_s.size < {{{minLength}}}
raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, the character length must be great than or equal to {{{minLength}}}.") raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, the character length must be great than or equal to {{{minLength}}}.")
end end
@ -111,13 +111,13 @@ module {{moduleName}}
{{/pattern}} {{/pattern}}
{{#maxItems}} {{#maxItems}}
if @api_client.config.client_side_validation && {{^required}}{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.length > {{{maxItems}}} if @api_client.config.client_side_validation && {{^required}}{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.size > {{{maxItems}}}
raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{{maxItems}}}.") raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{{maxItems}}}.")
end end
{{/maxItems}} {{/maxItems}}
{{#minItems}} {{#minItems}}
if @api_client.config.client_side_validation && {{^required}}{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.length < {{{minItems}}} if @api_client.config.client_side_validation && {{^required}}{{{paramName}}}.nil? && {{/required}}{{{paramName}}}.size < {{{minItems}}}
raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{{minItems}}}.") raise ArgumentError.new("invalid value for \"{{{paramName}}}\" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{{minItems}}}.")
end end
@ -130,7 +130,7 @@ module {{moduleName}}
# query parameters # query parameters
query_params = Hash(String, String).new query_params = Hash(String, String).new
{{#queryParams}} {{#queryParams}}
query_params["{{{baseName}}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}} query_params["{{{baseName}}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}.to_s unless {{{paramName}}}.nil?{{/collectionFormat}}
{{/queryParams}} {{/queryParams}}
# header parameters # header parameters
@ -148,9 +148,9 @@ module {{moduleName}}
{{/headerParams}} {{/headerParams}}
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
{{#formParams}} {{#formParams}}
form_params[:"{{baseName}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}} form_params[:"{{baseName}}"] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}} unless {{{paramName}}}.nil?{{/collectionFormat}}
{{/formParams}} {{/formParams}}
# http body (model) # http body (model)

View File

@ -38,118 +38,6 @@ module {{moduleName}}
(mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
end end
# Deserialize the response to the given return type.
#
# @param [Response] response HTTP response
# @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
def deserialize(response, return_type)
body = response.body
# handle file downloading - return the File instance processed in request callbacks
# note that response body is empty when the file is written in chunks in request on_body callback
if return_type == "File"
content_disposition = response.headers["Content-Disposition"].to_s
if content_disposition && content_disposition =~ /filename=/i
filename = content_disposition.match(/filename=[""]?([^""\s]+)[""]?/i).try &.[0]
prefix = sanitize_filename(filename)
else
prefix = "download-"
end
if !prefix.nil? && prefix.ends_with?("-")
prefix = prefix + "-"
end
encoding = response.headers["Content-Encoding"].to_s
# TODO add file support
raise ApiError.new(code: 0, message: "File response not yet supported in the client.") if return_type
return nil
#@tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
#@tempfile.write(@stream.join.force_encoding(encoding))
#@tempfile.close
#Log.info { "Temp file written to #{@tempfile.path}, please copy the file to a proper folder "\
# "with e.g. `FileUtils.cp(tempfile.path, \"/new/file/path\")` otherwise the temp file "\
# "will be deleted automatically with GC. It's also recommended to delete the temp file "\
# "explicitly with `tempfile.delete`" }
#return @tempfile
end
return nil if body.nil? || body.empty?
# return response body directly for String return type
return body if return_type == "String"
# ensuring a default content type
content_type = response.headers["Content-Type"] || "application/json"
raise ApiError.new(code: 0, message: "Content-Type is not supported: #{content_type}") unless json_mime?(content_type)
begin
data = JSON.parse("[#{body}]")[0]
rescue e : Exception
if %w(String Date Time).includes?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
# @param [Object] data Data to be converted
# @param [String] return_type Return type
# @return [Mixed] Data in a particular 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_s.to_i
when "Float"
data.to_s.to_f
when "Boolean"
data == true
when "Time"
# parse date time (expecting ISO 8601 format)
Time.parse! data.to_s, "%Y-%m-%dT%H:%M:%S%Z"
when "Date"
# parse date (expecting ISO 8601 format)
Time.parse! data.to_s, "%Y-%m-%d"
when "Object"
# generic object (usually a Hash), 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
({} of Symbol => String).tap do |hash|
data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models (e.g. Pet) or oneOf
klass = Petstore.const_get(return_type)
klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
end
end
# Sanitize filename by removing path.
# e.g. ../../sun.gif becomes sun.gif
#
# @param [String] filename the filename to be sanitized
# @return [String] the sanitized filename
def sanitize_filename(filename)
if filename.nil?
return nil
else
filename.gsub(/.*[\/\\]/, "")
end
end
def build_request_url(path : String, operation : Symbol) def build_request_url(path : String, operation : Symbol)
# Add leading and trailing slashes to path # Add leading and trailing slashes to path
@ -207,31 +95,6 @@ module {{moduleName}}
json_content_type || content_types.first json_content_type || content_types.first
end end
# Convert object (array, hash, object, etc) to JSON string.
# @param [Object] model object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_http_body(model)
return model if model.nil? || model.is_a?(String)
local_body = nil
if model.is_a?(Array)
local_body = model.map { |m| object_to_hash(m) }
else
local_body = object_to_hash(model)
end
local_body.to_json
end
# Convert object(non-array) to hash.
# @param [Object] obj object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_hash(obj)
if obj.respond_to?(:to_hash)
obj.to_hash
else
obj
end
end
# Build parameter value according to the given collection format. # Build parameter value according to the given collection format.
# @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
def build_collection_param(param, collection_format) def build_collection_param(param, collection_format)
@ -245,10 +108,10 @@ module {{moduleName}}
when :pipes when :pipes
param.join("|") param.join("|")
when :multi when :multi
# return the array directly as typhoeus will handle it as expected # TODO: Need to fix this
param raise "multi is not supported yet"
else else
fail "unknown collection format: #{collection_format.inspect}" raise "unknown collection format: #{collection_format.inspect}"
end end
end end
@ -256,7 +119,7 @@ module {{moduleName}}
# #
# @return [Array<(Object, Integer, Hash)>] an array of 3 elements: # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
# the data deserialized from response body (could be nil), response status code and response headers. # the data deserialized from response body (could be nil), response status code and response headers.
def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of String => String, form_params = {} of Symbol => String) def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String?, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of String => String, form_params = {} of Symbol => (String | ::File))
#ssl_options = { #ssl_options = {
# :ca_file => @config.ssl_ca_file, # :ca_file => @config.ssl_ca_file,
# :verify => @config.ssl_verify, # :verify => @config.ssl_verify,
@ -265,15 +128,6 @@ module {{moduleName}}
# :client_key => @config.ssl_client_key # :client_key => @config.ssl_client_key
#} #}
#connection = Faraday.new(:url => config.base_url, :ssl => ssl_options) do |conn|
# conn.basic_auth(config.username, config.password)
# if opts[:header_params]["Content-Type"] == "multipart/form-data"
# conn.request :multipart
# conn.request :url_encoded
# end
# conn.adapter(Faraday.default_adapter)
#end
update_params_for_auth! header_params, query_params, auth_names update_params_for_auth! header_params, query_params, auth_names
if !post_body.nil? && !post_body.empty? if !post_body.nil? && !post_body.empty?
@ -315,90 +169,5 @@ module {{moduleName}}
return response.body, response.status_code, response.headers return response.body, response.status_code, response.headers
end end
# Builds the HTTP request
#
# @param [String] http_method HTTP method/verb (e.g. POST)
# @param [String] path URL path (e.g. /account/new)
# @option opts [Hash] :header_params Header parameters
# @option opts [Hash] :query_params Query parameters
# @option opts [Hash] :form_params Query parameters
# @option opts [Object] :body HTTP body (JSON/XML)
# @return [Typhoeus::Request] A Typhoeus Request
def build_request(http_method, path, request, opts = {} of Symbol => String)
url = build_request_url(path, opts)
http_method = http_method.to_sym.downcase
header_params = @default_headers.merge(opts[:header_params] || {} of Symbole => String)
query_params = opts[:query_params] || {} of Symbol => String
form_params = opts[:form_params] || {} of Symbol => String
update_params_for_auth! header_params, query_params, opts[:auth_names]
req_opts = {
:method => http_method,
:headers => header_params,
:params => query_params,
:params_encoding => @config.params_encoding,
:timeout => @config.timeout,
:verbose => @config.debugging
}
if [:post, :patch, :put, :delete].includes?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update body: req_body
if @config.debugging
Log.debug {"HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"}
end
end
request.headers = header_params
request.body = req_body
request.url url
request.params = query_params
download_file(request) if opts[:return_type] == "File"
request
end
# Builds the HTTP request body
#
# @param [Hash] header_params Header parameters
# @param [Hash] form_params Query parameters
# @param [Object] body HTTP body (JSON/XML)
# @return [String] HTTP body data in the form of string
def build_request_body(header_params, form_params, body)
# http form
if header_params["Content-Type"] == "application/x-www-form-urlencoded"
data = URI.encode_www_form(form_params)
elsif header_params["Content-Type"] == "multipart/form-data"
data = {} of Symbol => String
form_params.each do |key, value|
case value
when ::File, ::Tempfile
# TODO hardcode to application/octet-stream, need better way to detect content type
data[key] = Faraday::UploadIO.new(value.path, "application/octet-stream", value.path)
when ::Array, nil
# let Faraday handle Array and nil parameters
data[key] = value
else
data[key] = value.to_s
end
end
elsif body
data = body.is_a?(String) ? body : body.to_json
else
data = nil
end
data
end
# TODO fix streaming response
#def download_file(request)
# @stream = []
# # handle streaming Responses
# request.options.on_data = Proc.new do |chunk, overall_received_bytes|
# @stream << chunk
# end
#end
end end
end end

View File

@ -1,153 +0,0 @@
# Call an API with given options.
#
# @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
# the data deserialized from response body (could be nil), response status code and response headers.
def call_api(http_method, path, opts = {} of Symbol => String)
request = build_request(http_method, path, opts)
response = request.run
if @config.debugging
@config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
end
unless response.success?
if response.timed_out?
fail ApiError.new("Connection timed out")
elsif response.code == 0
# Errors from libcurl will be made visible here
fail ApiError.new(code: 0,
message: response.return_message)
else
fail ApiError.new(code: response.code,
response_headers: response.headers,
response_body: response.body),
response.status_message
end
end
if opts[:return_type]
data = deserialize(response, opts[:return_type])
else
data = nil
end
return data, response.code, response.headers
end
# Builds the HTTP request
#
# @param [String] http_method HTTP method/verb (e.g. POST)
# @param [String] path URL path (e.g. /account/new)
# @option opts [Hash] :header_params Header parameters
# @option opts [Hash] :query_params Query parameters
# @option opts [Hash] :form_params Query parameters
# @option opts [Object] :body HTTP body (JSON/XML)
# @return [Typhoeus::Request] A Typhoeus Request
def build_request(http_method, path, opts = {} of Symbol => String)
url = build_request_url(path, opts)
http_method = http_method.to_sym.downcase
header_params = @default_headers.merge(opts[:header_params] || {} of Symbol => String)
query_params = opts[:query_params] || {} of Symbol => String
form_params = opts[:form_params] || {} of Symbol => String
{{#hasAuthMethods}}
update_params_for_auth! header_params, query_params, opts[:auth_names]
{{/hasAuthMethods}}
# set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
_verify_ssl_host = @config.verify_ssl_host ? 2 : 0
req_opts = {
:method => http_method,
:headers => header_params,
:params => query_params,
:params_encoding => @config.params_encoding,
:timeout => @config.timeout,
:ssl_verifypeer => @config.verify_ssl,
:ssl_verifyhost => _verify_ssl_host,
:sslcert => @config.cert_file,
:sslkey => @config.key_file,
:verbose => @config.debugging
}
# set custom cert, if provided
req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
if [:post, :patch, :put, :delete].includes?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update body: req_body
if @config.debugging
@config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
end
end
request = Typhoeus::Request.new(url, req_opts)
download_file(request) if opts[:return_type] == "File"
request
end
# Builds the HTTP request body
#
# @param [Hash] header_params Header parameters
# @param [Hash] form_params Query parameters
# @param [Object] body HTTP body (JSON/XML)
# @return [String] HTTP body data in the form of string
def build_request_body(header_params, form_params, body)
# http form
if header_params["Content-Type"] == "application/x-www-form-urlencoded" ||
header_params["Content-Type"] == "multipart/form-data"
data = {} of Symbol => String
form_params.each do |key, value|
case value
when ::File, ::Array, nil
# let typhoeus handle File, Array and nil parameters
data[key] = value
else
data[key] = value.to_s
end
end
elsif body
data = body.is_a?(String) ? body : body.to_json
else
data = nil
end
data
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.
# The response body is written to the file in chunks in order to handle files which
# size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
# process can use.
#
# @see Configuration#temp_folder_path
def download_file(request)
tempfile = nil
encoding = nil
request.on_headers do |response|
content_disposition = response.headers["Content-Disposition"]
if content_disposition && content_disposition =~ /filename=/i
filename = content_disposition[/filename=[""]?([^""\s]+)[""]?/, 1]
prefix = sanitize_filename(filename)
else
prefix = "download-"
end
prefix = prefix + "-" unless prefix.end_with?("-")
encoding = response.body.encoding
tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
@tempfile = tempfile
end
request.on_body do |chunk|
chunk.force_encoding(encoding)
tempfile.write(chunk)
end
request.on_complete do |response|
if tempfile
tempfile.close
@config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
"with e.g. `FileUtils.cp(tempfile.path, \"/new/file/path\")` otherwise the temp file "\
"will be deleted automatically with GC. It's also recommended to delete the temp file "\
"explicitly with `tempfile.delete`"
end
end
end

View File

@ -263,7 +263,7 @@ module {{moduleName}}
{{#-first}} {{#-first}}
variables: { variables: {
{{/-first}} {{/-first}}
{{{name}}}: { "{{{name}}}": {
description: "{{{description}}}{{^description}}No description provided{{/description}}", description: "{{{description}}}{{^description}}No description provided{{/description}}",
default_value: "{{{defaultValue}}}", default_value: "{{{defaultValue}}}",
{{#enumValues}} {{#enumValues}}
@ -302,7 +302,7 @@ module {{moduleName}}
{{#-first}} {{#-first}}
variables: { variables: {
{{/-first}} {{/-first}}
{{{name}}}: { "{{{name}}}": {
description: "{{{description}}}{{^description}}No description provided{{/description}}", description: "{{{description}}}{{^description}}No description provided{{/description}}",
default_value: "{{{defaultValue}}}", default_value: "{{{defaultValue}}}",
{{#enumValues}} {{#enumValues}}

View File

@ -1,7 +1,6 @@
class {{classname}}{{#allowableValues}}{{#enumVars}} class {{classname}}{{#allowableValues}}{{#enumVars}}
{{{name}}} = {{{value}}}.freeze{{/enumVars}} {{{name}}} = {{{value}}}
{{/enumVars}} {{/allowableValues}}
{{/allowableValues}}
# Builds the enum from string # Builds the enum from string
# @param [String] The enum value in the form of the string # @param [String] The enum value in the form of the string
# @return [String] The enum value # @return [String] The enum value
@ -13,8 +12,11 @@
# @param [String] The enum value in the form of the string # @param [String] The enum value in the form of the string
# @return [String] The enum value # @return [String] The enum value
def build_from_hash(value) def build_from_hash(value)
constantValues = {{classname}}.constants.select { |c| {{classname}}::const_get(c) == value } case value{{#allowableValues}}{{#enumVars}}
raise "Invalid ENUM value #{value} for class #{{{classname}}}" if constantValues.empty? when {{{value}}}
value {{{name}}}{{/enumVars}}{{/allowableValues}}
else
raise "Invalid ENUM value #{value} for class #{{{classname}}}"
end
end end
end end

View File

@ -8,7 +8,7 @@
{{#description}} {{#description}}
# {{{.}}} # {{{.}}}
{{/description}} {{/description}}
@[JSON::Field(key: {{{baseName}}}, type: {{{dataType}}}{{#default}}, default: {{{.}}}{{/default}}{{#isNullable}}, nillable: true, emit_null: true{{/isNullable}})] @[JSON::Field(key: "{{{baseName}}}", type: {{{dataType}}}{{#defaultValue}}, default: {{{defaultValue}}}{{/defaultValue}}{{#isNullable}}, nillable: true, emit_null: true{{/isNullable}})]
property {{{name}}} : {{{dataType}}} property {{{name}}} : {{{dataType}}}
{{/vars}} {{/vars}}
@ -74,13 +74,13 @@
{{/discriminator}} {{/discriminator}}
# Initializes the object # Initializes the object
# @param [Hash] attributes Model attributes in the form of hash # @param [Hash] attributes Model attributes in the form of hash
def initialize({{#vars}}@{{{name}}} : {{{dataType}}}{{^required}} | Nil{{/required}}{{^-last}}, {{/-last}}{{/vars}}) def initialize({{#vars}}@{{{name}}} : {{{dataType}}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/vars}})
end end
# Show invalid properties with the reasons. Usually used together with valid? # Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons # @return Array for valid properties with the reasons
def list_invalid_properties def list_invalid_properties
invalid_properties = {{^parent}}Array.new{{/parent}}{{#parent}}super{{/parent}} invalid_properties = {{^parent}}Array(String).new{{/parent}}{{#parent}}super{{/parent}}
{{#vars}} {{#vars}}
{{^isNullable}} {{^isNullable}}
{{#required}} {{#required}}
@ -92,13 +92,13 @@
{{/isNullable}} {{/isNullable}}
{{#hasValidation}} {{#hasValidation}}
{{#maxLength}} {{#maxLength}}
if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length > {{{maxLength}}} if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.size > {{{maxLength}}}
invalid_properties.push("invalid value for \"{{{name}}}\", the character length must be smaller than or equal to {{{maxLength}}}.") invalid_properties.push("invalid value for \"{{{name}}}\", the character length must be smaller than or equal to {{{maxLength}}}.")
end end
{{/maxLength}} {{/maxLength}}
{{#minLength}} {{#minLength}}
if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length < {{{minLength}}} if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.size < {{{minLength}}}
invalid_properties.push("invalid value for \"{{{name}}}\", the character length must be great than or equal to {{{minLength}}}.") invalid_properties.push("invalid value for \"{{{name}}}\", the character length must be great than or equal to {{{minLength}}}.")
end end
@ -123,13 +123,13 @@
{{/pattern}} {{/pattern}}
{{#maxItems}} {{#maxItems}}
if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length > {{{maxItems}}} if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.size > {{{maxItems}}}
invalid_properties.push("invalid value for \"{{{name}}}\", number of items must be less than or equal to {{{maxItems}}}." invalid_properties.push("invalid value for \"{{{name}}}\", number of items must be less than or equal to {{{maxItems}}}."
end end
{{/maxItems}} {{/maxItems}}
{{#minItems}} {{#minItems}}
if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length < {{{minItems}}} if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.size < {{{minItems}}}
invalid_properties.push("invalid value for \"{{{name}}}\", number of items must be greater than or equal to {{{minItems}}}." invalid_properties.push("invalid value for \"{{{name}}}\", number of items must be greater than or equal to {{{minItems}}}."
end end
@ -156,10 +156,10 @@
{{/isEnum}} {{/isEnum}}
{{#hasValidation}} {{#hasValidation}}
{{#maxLength}} {{#maxLength}}
return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length > {{{maxLength}}} return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.size > {{{maxLength}}}
{{/maxLength}} {{/maxLength}}
{{#minLength}} {{#minLength}}
return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.length < {{{minLength}}} return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.to_s.size < {{{minLength}}}
{{/minLength}} {{/minLength}}
{{#maximum}} {{#maximum}}
return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}}
@ -171,10 +171,10 @@
return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} !~ Regexp.new({{{pattern}}}) return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}} !~ Regexp.new({{{pattern}}})
{{/pattern}} {{/pattern}}
{{#maxItems}} {{#maxItems}}
return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length > {{{maxItems}}} return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.size > {{{maxItems}}}
{{/maxItems}} {{/maxItems}}
{{#minItems}} {{#minItems}}
return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length < {{{minItems}}} return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.size < {{{minItems}}}
{{/minItems}} {{/minItems}}
{{/hasValidation}} {{/hasValidation}}
{{/vars}} {{/vars}}
@ -226,13 +226,13 @@
{{/required}} {{/required}}
{{/isNullable}} {{/isNullable}}
{{#maxLength}} {{#maxLength}}
if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.to_s.length > {{{maxLength}}} if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.to_s.size > {{{maxLength}}}
raise ArgumentError.new("invalid value for \"{{{name}}}\", the character length must be smaller than or equal to {{{maxLength}}}.") raise ArgumentError.new("invalid value for \"{{{name}}}\", the character length must be smaller than or equal to {{{maxLength}}}.")
end end
{{/maxLength}} {{/maxLength}}
{{#minLength}} {{#minLength}}
if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.to_s.length < {{{minLength}}} if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.to_s.size < {{{minLength}}}
raise ArgumentError.new("invalid value for \"{{{name}}}\", the character length must be great than or equal to {{{minLength}}}.") raise ArgumentError.new("invalid value for \"{{{name}}}\", the character length must be great than or equal to {{{minLength}}}.")
end end
@ -257,13 +257,13 @@
{{/pattern}} {{/pattern}}
{{#maxItems}} {{#maxItems}}
if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.length > {{{maxItems}}} if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.size > {{{maxItems}}}
raise ArgumentError.new("invalid value for \"{{{name}}}\", number of items must be less than or equal to {{{maxItems}}}.") raise ArgumentError.new("invalid value for \"{{{name}}}\", number of items must be less than or equal to {{{maxItems}}}.")
end end
{{/maxItems}} {{/maxItems}}
{{#minItems}} {{#minItems}}
if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.length < {{{minItems}}} if {{^required}}!{{{name}}}.nil? && {{/required}}{{{name}}}.size < {{{minItems}}}
raise ArgumentError.new("invalid value for \"{{{name}}}\", number of items must be greater than or equal to {{{minItems}}}.") raise ArgumentError.new("invalid value for \"{{{name}}}\", number of items must be greater than or equal to {{{minItems}}}.")
end end

View File

@ -50,7 +50,7 @@ module Petstore
header_params["Content-Type"] = @api_client.select_header_content_type(["application/json", "application/xml"]) header_params["Content-Type"] = @api_client.select_header_content_type(["application/json", "application/xml"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = pet.to_json post_body = pet.to_json
@ -106,7 +106,7 @@ module Petstore
header_params["api_key"] = api_key header_params["api_key"] = api_key
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -166,7 +166,7 @@ module Petstore
header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -226,7 +226,7 @@ module Petstore
header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -285,7 +285,7 @@ module Petstore
header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -344,7 +344,7 @@ module Petstore
header_params["Content-Type"] = @api_client.select_header_content_type(["application/json", "application/xml"]) header_params["Content-Type"] = @api_client.select_header_content_type(["application/json", "application/xml"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = pet.to_json post_body = pet.to_json
@ -401,9 +401,9 @@ module Petstore
header_params["Content-Type"] = @api_client.select_header_content_type(["application/x-www-form-urlencoded"]) header_params["Content-Type"] = @api_client.select_header_content_type(["application/x-www-form-urlencoded"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
form_params[:"name"] = name form_params[:"name"] = name unless name.nil?
form_params[:"status"] = status form_params[:"status"] = status unless status.nil?
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -432,7 +432,7 @@ module Petstore
# uploads an image # uploads an image
# @param pet_id [Int64] ID of pet to update # @param pet_id [Int64] ID of pet to update
# @return [ApiResponse] # @return [ApiResponse]
def upload_file(pet_id : Int64, additional_metadata : String?, file : File?) def upload_file(pet_id : Int64, additional_metadata : String?, file : ::File?)
data, _status_code, _headers = upload_file_with_http_info(pet_id, additional_metadata, file) data, _status_code, _headers = upload_file_with_http_info(pet_id, additional_metadata, file)
data data
end end
@ -440,7 +440,7 @@ module Petstore
# uploads an image # uploads an image
# @param pet_id [Int64] ID of pet to update # @param pet_id [Int64] ID of pet to update
# @return [Array<(ApiResponse, Integer, Hash)>] ApiResponse data, response status code and response headers # @return [Array<(ApiResponse, Integer, Hash)>] ApiResponse data, response status code and response headers
def upload_file_with_http_info(pet_id : Int64, additional_metadata : String?, file : File?) def upload_file_with_http_info(pet_id : Int64, additional_metadata : String?, file : ::File?)
if @api_client.config.debugging if @api_client.config.debugging
Log.debug {"Calling API: PetApi.upload_file ..."} Log.debug {"Calling API: PetApi.upload_file ..."}
end end
@ -462,9 +462,9 @@ module Petstore
header_params["Content-Type"] = @api_client.select_header_content_type(["multipart/form-data"]) header_params["Content-Type"] = @api_client.select_header_content_type(["multipart/form-data"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
form_params[:"additionalMetadata"] = additional_metadata form_params[:"additionalMetadata"] = additional_metadata unless additional_metadata.nil?
form_params[:"file"] = file form_params[:"file"] = file unless file.nil?
# http body (model) # http body (model)
post_body = nil post_body = nil

View File

@ -48,7 +48,7 @@ module Petstore
header_params = Hash(String, String).new header_params = Hash(String, String).new
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -101,7 +101,7 @@ module Petstore
header_params["Accept"] = @api_client.select_header_accept(["application/json"]) header_params["Accept"] = @api_client.select_header_accept(["application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -168,7 +168,7 @@ module Petstore
header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -227,7 +227,7 @@ module Petstore
header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = order.to_json post_body = order.to_json

View File

@ -50,7 +50,7 @@ module Petstore
header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = user.to_json post_body = user.to_json
@ -107,7 +107,7 @@ module Petstore
header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = user.to_json post_body = user.to_json
@ -164,7 +164,7 @@ module Petstore
header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = user.to_json post_body = user.to_json
@ -221,7 +221,7 @@ module Petstore
header_params = Hash(String, String).new header_params = Hash(String, String).new
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -278,7 +278,7 @@ module Petstore
header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -339,8 +339,8 @@ module Petstore
# query parameters # query parameters
query_params = Hash(String, String).new query_params = Hash(String, String).new
query_params["username"] = username query_params["username"] = username.to_s unless username.nil?
query_params["password"] = password query_params["password"] = password.to_s unless password.nil?
# header parameters # header parameters
header_params = Hash(String, String).new header_params = Hash(String, String).new
@ -348,7 +348,7 @@ module Petstore
header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -397,7 +397,7 @@ module Petstore
header_params = Hash(String, String).new header_params = Hash(String, String).new
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = nil post_body = nil
@ -462,7 +462,7 @@ module Petstore
header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"])
# form parameters # form parameters
form_params = Hash(Symbol, String).new form_params = Hash(Symbol, (String | ::File)).new
# http body (model) # http body (model)
post_body = user.to_json post_body = user.to_json

View File

@ -46,118 +46,6 @@ module Petstore
(mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
end end
# Deserialize the response to the given return type.
#
# @param [Response] response HTTP response
# @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
def deserialize(response, return_type)
body = response.body
# handle file downloading - return the File instance processed in request callbacks
# note that response body is empty when the file is written in chunks in request on_body callback
if return_type == "File"
content_disposition = response.headers["Content-Disposition"].to_s
if content_disposition && content_disposition =~ /filename=/i
filename = content_disposition.match(/filename=[""]?([^""\s]+)[""]?/i).try &.[0]
prefix = sanitize_filename(filename)
else
prefix = "download-"
end
if !prefix.nil? && prefix.ends_with?("-")
prefix = prefix + "-"
end
encoding = response.headers["Content-Encoding"].to_s
# TODO add file support
raise ApiError.new(code: 0, message: "File response not yet supported in the client.") if return_type
return nil
#@tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
#@tempfile.write(@stream.join.force_encoding(encoding))
#@tempfile.close
#Log.info { "Temp file written to #{@tempfile.path}, please copy the file to a proper folder "\
# "with e.g. `FileUtils.cp(tempfile.path, \"/new/file/path\")` otherwise the temp file "\
# "will be deleted automatically with GC. It's also recommended to delete the temp file "\
# "explicitly with `tempfile.delete`" }
#return @tempfile
end
return nil if body.nil? || body.empty?
# return response body directly for String return type
return body if return_type == "String"
# ensuring a default content type
content_type = response.headers["Content-Type"] || "application/json"
raise ApiError.new(code: 0, message: "Content-Type is not supported: #{content_type}") unless json_mime?(content_type)
begin
data = JSON.parse("[#{body}]")[0]
rescue e : Exception
if %w(String Date Time).includes?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
# @param [Object] data Data to be converted
# @param [String] return_type Return type
# @return [Mixed] Data in a particular 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_s.to_i
when "Float"
data.to_s.to_f
when "Boolean"
data == true
when "Time"
# parse date time (expecting ISO 8601 format)
Time.parse! data.to_s, "%Y-%m-%dT%H:%M:%S%Z"
when "Date"
# parse date (expecting ISO 8601 format)
Time.parse! data.to_s, "%Y-%m-%d"
when "Object"
# generic object (usually a Hash), 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
({} of Symbol => String).tap do |hash|
data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models (e.g. Pet) or oneOf
klass = Petstore.const_get(return_type)
klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
end
end
# Sanitize filename by removing path.
# e.g. ../../sun.gif becomes sun.gif
#
# @param [String] filename the filename to be sanitized
# @return [String] the sanitized filename
def sanitize_filename(filename)
if filename.nil?
return nil
else
filename.gsub(/.*[\/\\]/, "")
end
end
def build_request_url(path : String, operation : Symbol) def build_request_url(path : String, operation : Symbol)
# Add leading and trailing slashes to path # Add leading and trailing slashes to path
@ -215,31 +103,6 @@ module Petstore
json_content_type || content_types.first json_content_type || content_types.first
end end
# Convert object (array, hash, object, etc) to JSON string.
# @param [Object] model object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_http_body(model)
return model if model.nil? || model.is_a?(String)
local_body = nil
if model.is_a?(Array)
local_body = model.map { |m| object_to_hash(m) }
else
local_body = object_to_hash(model)
end
local_body.to_json
end
# Convert object(non-array) to hash.
# @param [Object] obj object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_hash(obj)
if obj.respond_to?(:to_hash)
obj.to_hash
else
obj
end
end
# Build parameter value according to the given collection format. # Build parameter value according to the given collection format.
# @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
def build_collection_param(param, collection_format) def build_collection_param(param, collection_format)
@ -253,10 +116,10 @@ module Petstore
when :pipes when :pipes
param.join("|") param.join("|")
when :multi when :multi
# return the array directly as typhoeus will handle it as expected # TODO: Need to fix this
param raise "multi is not supported yet"
else else
fail "unknown collection format: #{collection_format.inspect}" raise "unknown collection format: #{collection_format.inspect}"
end end
end end
@ -264,7 +127,7 @@ module Petstore
# #
# @return [Array<(Object, Integer, Hash)>] an array of 3 elements: # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
# the data deserialized from response body (could be nil), response status code and response headers. # the data deserialized from response body (could be nil), response status code and response headers.
def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of String => String, form_params = {} of Symbol => String) def call_api(http_method : Symbol, path : String, operation : Symbol, return_type : String?, post_body : String?, auth_names = [] of String, header_params = {} of String => String, query_params = {} of String => String, form_params = {} of Symbol => (String | ::File))
#ssl_options = { #ssl_options = {
# :ca_file => @config.ssl_ca_file, # :ca_file => @config.ssl_ca_file,
# :verify => @config.ssl_verify, # :verify => @config.ssl_verify,
@ -273,15 +136,6 @@ module Petstore
# :client_key => @config.ssl_client_key # :client_key => @config.ssl_client_key
#} #}
#connection = Faraday.new(:url => config.base_url, :ssl => ssl_options) do |conn|
# conn.basic_auth(config.username, config.password)
# if opts[:header_params]["Content-Type"] == "multipart/form-data"
# conn.request :multipart
# conn.request :url_encoded
# end
# conn.adapter(Faraday.default_adapter)
#end
update_params_for_auth! header_params, query_params, auth_names update_params_for_auth! header_params, query_params, auth_names
if !post_body.nil? && !post_body.empty? if !post_body.nil? && !post_body.empty?
@ -323,90 +177,5 @@ module Petstore
return response.body, response.status_code, response.headers return response.body, response.status_code, response.headers
end end
# Builds the HTTP request
#
# @param [String] http_method HTTP method/verb (e.g. POST)
# @param [String] path URL path (e.g. /account/new)
# @option opts [Hash] :header_params Header parameters
# @option opts [Hash] :query_params Query parameters
# @option opts [Hash] :form_params Query parameters
# @option opts [Object] :body HTTP body (JSON/XML)
# @return [Typhoeus::Request] A Typhoeus Request
def build_request(http_method, path, request, opts = {} of Symbol => String)
url = build_request_url(path, opts)
http_method = http_method.to_sym.downcase
header_params = @default_headers.merge(opts[:header_params] || {} of Symbole => String)
query_params = opts[:query_params] || {} of Symbol => String
form_params = opts[:form_params] || {} of Symbol => String
update_params_for_auth! header_params, query_params, opts[:auth_names]
req_opts = {
:method => http_method,
:headers => header_params,
:params => query_params,
:params_encoding => @config.params_encoding,
:timeout => @config.timeout,
:verbose => @config.debugging
}
if [:post, :patch, :put, :delete].includes?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update body: req_body
if @config.debugging
Log.debug {"HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"}
end
end
request.headers = header_params
request.body = req_body
request.url url
request.params = query_params
download_file(request) if opts[:return_type] == "File"
request
end
# Builds the HTTP request body
#
# @param [Hash] header_params Header parameters
# @param [Hash] form_params Query parameters
# @param [Object] body HTTP body (JSON/XML)
# @return [String] HTTP body data in the form of string
def build_request_body(header_params, form_params, body)
# http form
if header_params["Content-Type"] == "application/x-www-form-urlencoded"
data = URI.encode_www_form(form_params)
elsif header_params["Content-Type"] == "multipart/form-data"
data = {} of Symbol => String
form_params.each do |key, value|
case value
when ::File, ::Tempfile
# TODO hardcode to application/octet-stream, need better way to detect content type
data[key] = Faraday::UploadIO.new(value.path, "application/octet-stream", value.path)
when ::Array, nil
# let Faraday handle Array and nil parameters
data[key] = value
else
data[key] = value.to_s
end
end
elsif body
data = body.is_a?(String) ? body : body.to_json
else
data = nil
end
data
end
# TODO fix streaming response
#def download_file(request)
# @stream = []
# # handle streaming Responses
# request.options.on_data = Proc.new do |chunk, overall_received_bytes|
# @stream << chunk
# end
#end
end end
end end

View File

@ -16,24 +16,24 @@ module Petstore
class ApiResponse class ApiResponse
include JSON::Serializable include JSON::Serializable
@[JSON::Field(key: code, type: Int32)] @[JSON::Field(key: "code", type: Int32)]
property code : Int32 property code : Int32
@[JSON::Field(key: type, type: String)] @[JSON::Field(key: "type", type: String)]
property _type : String property _type : String
@[JSON::Field(key: message, type: String)] @[JSON::Field(key: "message", type: String)]
property message : String property message : String
# Initializes the object # Initializes the object
# @param [Hash] attributes Model attributes in the form of hash # @param [Hash] attributes Model attributes in the form of hash
def initialize(@code : Int32 | Nil, @_type : String | Nil, @message : String | Nil) def initialize(@code : Int32?, @_type : String?, @message : String?)
end end
# Show invalid properties with the reasons. Usually used together with valid? # Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons # @return Array for valid properties with the reasons
def list_invalid_properties def list_invalid_properties
invalid_properties = Array.new invalid_properties = Array(String).new
invalid_properties invalid_properties
end end

View File

@ -16,21 +16,21 @@ module Petstore
class Category class Category
include JSON::Serializable include JSON::Serializable
@[JSON::Field(key: id, type: Int64)] @[JSON::Field(key: "id", type: Int64)]
property id : Int64 property id : Int64
@[JSON::Field(key: name, type: String)] @[JSON::Field(key: "name", type: String)]
property name : String property name : String
# Initializes the object # Initializes the object
# @param [Hash] attributes Model attributes in the form of hash # @param [Hash] attributes Model attributes in the form of hash
def initialize(@id : Int64 | Nil, @name : String | Nil) def initialize(@id : Int64?, @name : String?)
end end
# Show invalid properties with the reasons. Usually used together with valid? # Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons # @return Array for valid properties with the reasons
def list_invalid_properties def list_invalid_properties
invalid_properties = Array.new invalid_properties = Array(String).new
pattern = Regexp.new(/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/) pattern = Regexp.new(/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/)
if !@name.nil? && @name !~ pattern if !@name.nil? && @name !~ pattern
invalid_properties.push("invalid value for \"name\", must conform to the pattern #{pattern}.") invalid_properties.push("invalid value for \"name\", must conform to the pattern #{pattern}.")

View File

@ -16,23 +16,23 @@ module Petstore
class Order class Order
include JSON::Serializable include JSON::Serializable
@[JSON::Field(key: id, type: Int64)] @[JSON::Field(key: "id", type: Int64)]
property id : Int64 property id : Int64
@[JSON::Field(key: petId, type: Int64)] @[JSON::Field(key: "petId", type: Int64)]
property pet_id : Int64 property pet_id : Int64
@[JSON::Field(key: quantity, type: Int32)] @[JSON::Field(key: "quantity", type: Int32)]
property quantity : Int32 property quantity : Int32
@[JSON::Field(key: shipDate, type: Time)] @[JSON::Field(key: "shipDate", type: Time)]
property ship_date : Time property ship_date : Time
# Order Status # Order Status
@[JSON::Field(key: status, type: String)] @[JSON::Field(key: "status", type: String)]
property status : String property status : String
@[JSON::Field(key: complete, type: Bool)] @[JSON::Field(key: "complete", type: Bool, default: false)]
property complete : Bool property complete : Bool
class EnumAttributeValidator class EnumAttributeValidator
@ -60,13 +60,13 @@ module Petstore
# Initializes the object # Initializes the object
# @param [Hash] attributes Model attributes in the form of hash # @param [Hash] attributes Model attributes in the form of hash
def initialize(@id : Int64 | Nil, @pet_id : Int64 | Nil, @quantity : Int32 | Nil, @ship_date : Time | Nil, @status : String | Nil, @complete : Bool | Nil) def initialize(@id : Int64?, @pet_id : Int64?, @quantity : Int32?, @ship_date : Time?, @status : String?, @complete : Bool?)
end end
# Show invalid properties with the reasons. Usually used together with valid? # Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons # @return Array for valid properties with the reasons
def list_invalid_properties def list_invalid_properties
invalid_properties = Array.new invalid_properties = Array(String).new
invalid_properties invalid_properties
end end

View File

@ -16,23 +16,23 @@ module Petstore
class Pet class Pet
include JSON::Serializable include JSON::Serializable
@[JSON::Field(key: id, type: Int64)] @[JSON::Field(key: "id", type: Int64)]
property id : Int64 property id : Int64
@[JSON::Field(key: category, type: Category)] @[JSON::Field(key: "category", type: Category)]
property category : Category property category : Category
@[JSON::Field(key: name, type: String)] @[JSON::Field(key: "name", type: String)]
property name : String property name : String
@[JSON::Field(key: photoUrls, type: Array(String))] @[JSON::Field(key: "photoUrls", type: Array(String))]
property photo_urls : Array(String) property photo_urls : Array(String)
@[JSON::Field(key: tags, type: Array(Tag))] @[JSON::Field(key: "tags", type: Array(Tag))]
property tags : Array(Tag) property tags : Array(Tag)
# pet status in the store # pet status in the store
@[JSON::Field(key: status, type: String)] @[JSON::Field(key: "status", type: String)]
property status : String property status : String
class EnumAttributeValidator class EnumAttributeValidator
@ -60,13 +60,13 @@ module Petstore
# Initializes the object # Initializes the object
# @param [Hash] attributes Model attributes in the form of hash # @param [Hash] attributes Model attributes in the form of hash
def initialize(@id : Int64 | Nil, @category : Category | Nil, @name : String, @photo_urls : Array(String), @tags : Array(Tag) | Nil, @status : String | Nil) def initialize(@id : Int64?, @category : Category?, @name : String, @photo_urls : Array(String), @tags : Array(Tag)?, @status : String?)
end end
# Show invalid properties with the reasons. Usually used together with valid? # Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons # @return Array for valid properties with the reasons
def list_invalid_properties def list_invalid_properties
invalid_properties = Array.new invalid_properties = Array(String).new
if @name.nil? if @name.nil?
invalid_properties.push("invalid value for \"name\", name cannot be nil.") invalid_properties.push("invalid value for \"name\", name cannot be nil.")
end end

View File

@ -16,21 +16,21 @@ module Petstore
class Tag class Tag
include JSON::Serializable include JSON::Serializable
@[JSON::Field(key: id, type: Int64)] @[JSON::Field(key: "id", type: Int64)]
property id : Int64 property id : Int64
@[JSON::Field(key: name, type: String)] @[JSON::Field(key: "name", type: String)]
property name : String property name : String
# Initializes the object # Initializes the object
# @param [Hash] attributes Model attributes in the form of hash # @param [Hash] attributes Model attributes in the form of hash
def initialize(@id : Int64 | Nil, @name : String | Nil) def initialize(@id : Int64?, @name : String?)
end end
# Show invalid properties with the reasons. Usually used together with valid? # Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons # @return Array for valid properties with the reasons
def list_invalid_properties def list_invalid_properties
invalid_properties = Array.new invalid_properties = Array(String).new
invalid_properties invalid_properties
end end

View File

@ -16,40 +16,40 @@ module Petstore
class User class User
include JSON::Serializable include JSON::Serializable
@[JSON::Field(key: id, type: Int64)] @[JSON::Field(key: "id", type: Int64)]
property id : Int64 property id : Int64
@[JSON::Field(key: username, type: String)] @[JSON::Field(key: "username", type: String)]
property username : String property username : String
@[JSON::Field(key: firstName, type: String)] @[JSON::Field(key: "firstName", type: String)]
property first_name : String property first_name : String
@[JSON::Field(key: lastName, type: String)] @[JSON::Field(key: "lastName", type: String)]
property last_name : String property last_name : String
@[JSON::Field(key: email, type: String)] @[JSON::Field(key: "email", type: String)]
property email : String property email : String
@[JSON::Field(key: password, type: String)] @[JSON::Field(key: "password", type: String)]
property password : String property password : String
@[JSON::Field(key: phone, type: String)] @[JSON::Field(key: "phone", type: String)]
property phone : String property phone : String
# User Status # User Status
@[JSON::Field(key: userStatus, type: Int32)] @[JSON::Field(key: "userStatus", type: Int32)]
property user_status : Int32 property user_status : Int32
# Initializes the object # Initializes the object
# @param [Hash] attributes Model attributes in the form of hash # @param [Hash] attributes Model attributes in the form of hash
def initialize(@id : Int64 | Nil, @username : String | Nil, @first_name : String | Nil, @last_name : String | Nil, @email : String | Nil, @password : String | Nil, @phone : String | Nil, @user_status : Int32 | Nil) def initialize(@id : Int64?, @username : String?, @first_name : String?, @last_name : String?, @email : String?, @password : String?, @phone : String?, @user_status : Int32?)
end end
# Show invalid properties with the reasons. Usually used together with valid? # Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons # @return Array for valid properties with the reasons
def list_invalid_properties def list_invalid_properties
invalid_properties = Array.new invalid_properties = Array(String).new
invalid_properties invalid_properties
end end