From 27459b500349194c5d09cad4869c155924ba629c Mon Sep 17 00:00:00 2001 From: cyangle Date: Fri, 22 Oct 2021 22:34:08 -0500 Subject: [PATCH] [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 --- .../languages/CrystalClientCodegen.java | 6 +- .../src/main/resources/crystal/api.mustache | 14 +- .../resources/crystal/api_client.mustache | 239 +----------------- .../api_client_typhoeus_partial.mustache | 153 ----------- .../resources/crystal/configuration.mustache | 4 +- .../crystal/partial_model_enum_class.mustache | 14 +- .../crystal/partial_model_generic.mustache | 30 +-- .../crystal/src/petstore/api/pet_api.cr | 28 +- .../crystal/src/petstore/api/store_api.cr | 8 +- .../crystal/src/petstore/api/user_api.cr | 20 +- .../crystal/src/petstore/api_client.cr | 239 +----------------- .../src/petstore/models/api_response.cr | 10 +- .../crystal/src/petstore/models/category.cr | 8 +- .../crystal/src/petstore/models/order.cr | 16 +- .../crystal/src/petstore/models/pet.cr | 16 +- .../crystal/src/petstore/models/tag.cr | 8 +- .../crystal/src/petstore/models/user.cr | 20 +- 17 files changed, 110 insertions(+), 723 deletions(-) delete mode 100644 modules/openapi-generator/src/main/resources/crystal/api_client_typhoeus_partial.mustache diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java index c2d292b3828..203bed47040 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java @@ -153,7 +153,7 @@ public class CrystalClientCodegen extends DefaultCodegen { languageSpecificPrimitives.add("Time"); languageSpecificPrimitives.add("Array"); languageSpecificPrimitives.add("Hash"); - languageSpecificPrimitives.add("File"); + languageSpecificPrimitives.add("::File"); languageSpecificPrimitives.add("Object"); typeMapping.clear(); @@ -174,7 +174,7 @@ public class CrystalClientCodegen extends DefaultCodegen { typeMapping.put("set", "Set"); typeMapping.put("map", "Hash"); typeMapping.put("object", "Object"); - typeMapping.put("file", "File"); + typeMapping.put("file", "::File"); typeMapping.put("binary", "String"); typeMapping.put("ByteArray", "String"); typeMapping.put("UUID", "String"); @@ -802,7 +802,7 @@ public class CrystalClientCodegen extends DefaultCodegen { } else if (p.getDefault() instanceof java.time.OffsetDateTime) { return "Time.parse(\"" + String.format(Locale.ROOT, ((java.time.OffsetDateTime) p.getDefault()).atZoneSameInstant(ZoneId.systemDefault()).toString(), "") + "\")"; } else { - return "'" + escapeText((String) p.getDefault()) + "'"; + return "\"" + escapeText((String) p.getDefault()) + "\""; } } } diff --git a/modules/openapi-generator/src/main/resources/crystal/api.mustache b/modules/openapi-generator/src/main/resources/crystal/api.mustache index 81af036027e..28758d68a5f 100644 --- a/modules/openapi-generator/src/main/resources/crystal/api.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/api.mustache @@ -80,13 +80,13 @@ module {{moduleName}} {{/required}} {{#hasValidation}} {{#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}}}.") end {{/maxLength}} {{#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}}}.") end @@ -111,13 +111,13 @@ module {{moduleName}} {{/pattern}} {{#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}}}.") end {{/maxItems}} {{#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}}}.") end @@ -130,7 +130,7 @@ module {{moduleName}} # query parameters query_params = Hash(String, String).new {{#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}} # header parameters @@ -148,9 +148,9 @@ module {{moduleName}} {{/headerParams}} # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new {{#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}} # http body (model) diff --git a/modules/openapi-generator/src/main/resources/crystal/api_client.mustache b/modules/openapi-generator/src/main/resources/crystal/api_client.mustache index 7981d3f56f4..6092a89911c 100644 --- a/modules/openapi-generator/src/main/resources/crystal/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/api_client.mustache @@ -38,118 +38,6 @@ module {{moduleName}} (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? end - # Deserialize the response to the given return type. - # - # @param [Response] response HTTP response - # @param [String] return_type some examples: "User", "Array", "Hash" - 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 - sub_type = $1 - data.map { |item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - 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) # Add leading and trailing slashes to path @@ -207,31 +95,6 @@ module {{moduleName}} json_content_type || content_types.first 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. # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi def build_collection_param(param, collection_format) @@ -245,10 +108,10 @@ module {{moduleName}} when :pipes param.join("|") when :multi - # return the array directly as typhoeus will handle it as expected - param + # TODO: Need to fix this + raise "multi is not supported yet" else - fail "unknown collection format: #{collection_format.inspect}" + raise "unknown collection format: #{collection_format.inspect}" end end @@ -256,7 +119,7 @@ module {{moduleName}} # # @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 : 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 = { # :ca_file => @config.ssl_ca_file, # :verify => @config.ssl_verify, @@ -265,15 +128,6 @@ module {{moduleName}} # :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 if !post_body.nil? && !post_body.empty? @@ -315,90 +169,5 @@ module {{moduleName}} return response.body, response.status_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, 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 diff --git a/modules/openapi-generator/src/main/resources/crystal/api_client_typhoeus_partial.mustache b/modules/openapi-generator/src/main/resources/crystal/api_client_typhoeus_partial.mustache deleted file mode 100644 index e076e92c9fd..00000000000 --- a/modules/openapi-generator/src/main/resources/crystal/api_client_typhoeus_partial.mustache +++ /dev/null @@ -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 diff --git a/modules/openapi-generator/src/main/resources/crystal/configuration.mustache b/modules/openapi-generator/src/main/resources/crystal/configuration.mustache index 103cf1820b2..a63e86ee876 100644 --- a/modules/openapi-generator/src/main/resources/crystal/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/configuration.mustache @@ -263,7 +263,7 @@ module {{moduleName}} {{#-first}} variables: { {{/-first}} - {{{name}}}: { + "{{{name}}}": { description: "{{{description}}}{{^description}}No description provided{{/description}}", default_value: "{{{defaultValue}}}", {{#enumValues}} @@ -302,7 +302,7 @@ module {{moduleName}} {{#-first}} variables: { {{/-first}} - {{{name}}}: { + "{{{name}}}": { description: "{{{description}}}{{^description}}No description provided{{/description}}", default_value: "{{{defaultValue}}}", {{#enumValues}} diff --git a/modules/openapi-generator/src/main/resources/crystal/partial_model_enum_class.mustache b/modules/openapi-generator/src/main/resources/crystal/partial_model_enum_class.mustache index 4b8b5a0ffda..02da11897ad 100644 --- a/modules/openapi-generator/src/main/resources/crystal/partial_model_enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/partial_model_enum_class.mustache @@ -1,7 +1,6 @@ class {{classname}}{{#allowableValues}}{{#enumVars}} - {{{name}}} = {{{value}}}.freeze{{/enumVars}} - -{{/allowableValues}} + {{{name}}} = {{{value}}} + {{/enumVars}} {{/allowableValues}} # Builds the enum from string # @param [String] The enum value in the form of the string # @return [String] The enum value @@ -13,8 +12,11 @@ # @param [String] The enum value in the form of the string # @return [String] The enum value def build_from_hash(value) - constantValues = {{classname}}.constants.select { |c| {{classname}}::const_get(c) == value } - raise "Invalid ENUM value #{value} for class #{{{classname}}}" if constantValues.empty? - value + case value{{#allowableValues}}{{#enumVars}} + when {{{value}}} + {{{name}}}{{/enumVars}}{{/allowableValues}} + else + raise "Invalid ENUM value #{value} for class #{{{classname}}}" + end end end \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache b/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache index 2dfe0d7f17a..4f2de178b0e 100644 --- a/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/crystal/partial_model_generic.mustache @@ -8,7 +8,7 @@ {{#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}}} {{/vars}} @@ -74,13 +74,13 @@ {{/discriminator}} # Initializes the object # @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 # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties - invalid_properties = {{^parent}}Array.new{{/parent}}{{#parent}}super{{/parent}} + invalid_properties = {{^parent}}Array(String).new{{/parent}}{{#parent}}super{{/parent}} {{#vars}} {{^isNullable}} {{#required}} @@ -92,13 +92,13 @@ {{/isNullable}} {{#hasValidation}} {{#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}}}.") end {{/maxLength}} {{#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}}}.") end @@ -123,13 +123,13 @@ {{/pattern}} {{#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}}}." end {{/maxItems}} {{#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}}}." end @@ -156,10 +156,10 @@ {{/isEnum}} {{#hasValidation}} {{#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}} {{#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}} {{#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}}}) {{/pattern}} {{#maxItems}} - return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length > {{{maxItems}}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.size > {{{maxItems}}} {{/maxItems}} {{#minItems}} - return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.length < {{{minItems}}} + return false if {{^required}}!@{{{name}}}.nil? && {{/required}}@{{{name}}}.size < {{{minItems}}} {{/minItems}} {{/hasValidation}} {{/vars}} @@ -226,13 +226,13 @@ {{/required}} {{/isNullable}} {{#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}}}.") end {{/maxLength}} {{#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}}}.") end @@ -257,13 +257,13 @@ {{/pattern}} {{#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}}}.") end {{/maxItems}} {{#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}}}.") end diff --git a/samples/client/petstore/crystal/src/petstore/api/pet_api.cr b/samples/client/petstore/crystal/src/petstore/api/pet_api.cr index fe57b6a3394..058fc976e5c 100644 --- a/samples/client/petstore/crystal/src/petstore/api/pet_api.cr +++ b/samples/client/petstore/crystal/src/petstore/api/pet_api.cr @@ -50,7 +50,7 @@ module Petstore header_params["Content-Type"] = @api_client.select_header_content_type(["application/json", "application/xml"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = pet.to_json @@ -106,7 +106,7 @@ module Petstore header_params["api_key"] = api_key # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -166,7 +166,7 @@ module Petstore header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -226,7 +226,7 @@ module Petstore header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -285,7 +285,7 @@ module Petstore header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -344,7 +344,7 @@ module Petstore header_params["Content-Type"] = @api_client.select_header_content_type(["application/json", "application/xml"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) 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"]) # form parameters - form_params = Hash(Symbol, String).new - form_params[:"name"] = name - form_params[:"status"] = status + form_params = Hash(Symbol, (String | ::File)).new + form_params[:"name"] = name unless name.nil? + form_params[:"status"] = status unless status.nil? # http body (model) post_body = nil @@ -432,7 +432,7 @@ module Petstore # uploads an image # @param pet_id [Int64] ID of pet to update # @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 end @@ -440,7 +440,7 @@ module Petstore # uploads an image # @param pet_id [Int64] ID of pet to update # @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 Log.debug {"Calling API: PetApi.upload_file ..."} end @@ -462,9 +462,9 @@ module Petstore header_params["Content-Type"] = @api_client.select_header_content_type(["multipart/form-data"]) # form parameters - form_params = Hash(Symbol, String).new - form_params[:"additionalMetadata"] = additional_metadata - form_params[:"file"] = file + form_params = Hash(Symbol, (String | ::File)).new + form_params[:"additionalMetadata"] = additional_metadata unless additional_metadata.nil? + form_params[:"file"] = file unless file.nil? # http body (model) post_body = nil diff --git a/samples/client/petstore/crystal/src/petstore/api/store_api.cr b/samples/client/petstore/crystal/src/petstore/api/store_api.cr index 7a1d0e197b2..cb65b9b0761 100644 --- a/samples/client/petstore/crystal/src/petstore/api/store_api.cr +++ b/samples/client/petstore/crystal/src/petstore/api/store_api.cr @@ -48,7 +48,7 @@ module Petstore header_params = Hash(String, String).new # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -101,7 +101,7 @@ module Petstore header_params["Accept"] = @api_client.select_header_accept(["application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -168,7 +168,7 @@ module Petstore header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -227,7 +227,7 @@ module Petstore header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = order.to_json diff --git a/samples/client/petstore/crystal/src/petstore/api/user_api.cr b/samples/client/petstore/crystal/src/petstore/api/user_api.cr index ed913ab049a..6ca5f1716bd 100644 --- a/samples/client/petstore/crystal/src/petstore/api/user_api.cr +++ b/samples/client/petstore/crystal/src/petstore/api/user_api.cr @@ -50,7 +50,7 @@ module Petstore header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = user.to_json @@ -107,7 +107,7 @@ module Petstore header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = user.to_json @@ -164,7 +164,7 @@ module Petstore header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = user.to_json @@ -221,7 +221,7 @@ module Petstore header_params = Hash(String, String).new # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -278,7 +278,7 @@ module Petstore header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -339,8 +339,8 @@ module Petstore # query parameters query_params = Hash(String, String).new - query_params["username"] = username - query_params["password"] = password + query_params["username"] = username.to_s unless username.nil? + query_params["password"] = password.to_s unless password.nil? # header parameters header_params = Hash(String, String).new @@ -348,7 +348,7 @@ module Petstore header_params["Accept"] = @api_client.select_header_accept(["application/xml", "application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -397,7 +397,7 @@ module Petstore header_params = Hash(String, String).new # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = nil @@ -462,7 +462,7 @@ module Petstore header_params["Content-Type"] = @api_client.select_header_content_type(["application/json"]) # form parameters - form_params = Hash(Symbol, String).new + form_params = Hash(Symbol, (String | ::File)).new # http body (model) post_body = user.to_json diff --git a/samples/client/petstore/crystal/src/petstore/api_client.cr b/samples/client/petstore/crystal/src/petstore/api_client.cr index 0f309645957..1ee822d6f9b 100644 --- a/samples/client/petstore/crystal/src/petstore/api_client.cr +++ b/samples/client/petstore/crystal/src/petstore/api_client.cr @@ -46,118 +46,6 @@ module Petstore (mime == "*/*") || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? end - # Deserialize the response to the given return type. - # - # @param [Response] response HTTP response - # @param [String] return_type some examples: "User", "Array", "Hash" - 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 - sub_type = $1 - data.map { |item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - 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) # Add leading and trailing slashes to path @@ -215,31 +103,6 @@ module Petstore json_content_type || content_types.first 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. # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi def build_collection_param(param, collection_format) @@ -253,10 +116,10 @@ module Petstore when :pipes param.join("|") when :multi - # return the array directly as typhoeus will handle it as expected - param + # TODO: Need to fix this + raise "multi is not supported yet" else - fail "unknown collection format: #{collection_format.inspect}" + raise "unknown collection format: #{collection_format.inspect}" end end @@ -264,7 +127,7 @@ module Petstore # # @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 : 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 = { # :ca_file => @config.ssl_ca_file, # :verify => @config.ssl_verify, @@ -273,15 +136,6 @@ module Petstore # :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 if !post_body.nil? && !post_body.empty? @@ -323,90 +177,5 @@ module Petstore return response.body, response.status_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, 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 diff --git a/samples/client/petstore/crystal/src/petstore/models/api_response.cr b/samples/client/petstore/crystal/src/petstore/models/api_response.cr index ddaa7004271..9cfdeb12f39 100644 --- a/samples/client/petstore/crystal/src/petstore/models/api_response.cr +++ b/samples/client/petstore/crystal/src/petstore/models/api_response.cr @@ -16,24 +16,24 @@ module Petstore class ApiResponse include JSON::Serializable - @[JSON::Field(key: code, type: Int32)] + @[JSON::Field(key: "code", type: Int32)] property code : Int32 - @[JSON::Field(key: type, type: String)] + @[JSON::Field(key: "type", type: String)] property _type : String - @[JSON::Field(key: message, type: String)] + @[JSON::Field(key: "message", type: String)] property message : String # Initializes the object # @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 # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties - invalid_properties = Array.new + invalid_properties = Array(String).new invalid_properties end diff --git a/samples/client/petstore/crystal/src/petstore/models/category.cr b/samples/client/petstore/crystal/src/petstore/models/category.cr index fd6907a1d3a..0311aa78c58 100644 --- a/samples/client/petstore/crystal/src/petstore/models/category.cr +++ b/samples/client/petstore/crystal/src/petstore/models/category.cr @@ -16,21 +16,21 @@ module Petstore class Category include JSON::Serializable - @[JSON::Field(key: id, type: Int64)] + @[JSON::Field(key: "id", type: Int64)] property id : Int64 - @[JSON::Field(key: name, type: String)] + @[JSON::Field(key: "name", type: String)] property name : String # Initializes the object # @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 # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons 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]+$/) if !@name.nil? && @name !~ pattern invalid_properties.push("invalid value for \"name\", must conform to the pattern #{pattern}.") diff --git a/samples/client/petstore/crystal/src/petstore/models/order.cr b/samples/client/petstore/crystal/src/petstore/models/order.cr index 97c5ee66391..3c5f0e994ab 100644 --- a/samples/client/petstore/crystal/src/petstore/models/order.cr +++ b/samples/client/petstore/crystal/src/petstore/models/order.cr @@ -16,23 +16,23 @@ module Petstore class Order include JSON::Serializable - @[JSON::Field(key: id, type: Int64)] + @[JSON::Field(key: "id", type: Int64)] property id : Int64 - @[JSON::Field(key: petId, type: Int64)] + @[JSON::Field(key: "petId", type: Int64)] property pet_id : Int64 - @[JSON::Field(key: quantity, type: Int32)] + @[JSON::Field(key: "quantity", type: Int32)] property quantity : Int32 - @[JSON::Field(key: shipDate, type: Time)] + @[JSON::Field(key: "shipDate", type: Time)] property ship_date : Time # Order Status - @[JSON::Field(key: status, type: String)] + @[JSON::Field(key: "status", type: String)] property status : String - @[JSON::Field(key: complete, type: Bool)] + @[JSON::Field(key: "complete", type: Bool, default: false)] property complete : Bool class EnumAttributeValidator @@ -60,13 +60,13 @@ module Petstore # Initializes the object # @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 # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties - invalid_properties = Array.new + invalid_properties = Array(String).new invalid_properties end diff --git a/samples/client/petstore/crystal/src/petstore/models/pet.cr b/samples/client/petstore/crystal/src/petstore/models/pet.cr index 061a980ea53..2aa4abf8aca 100644 --- a/samples/client/petstore/crystal/src/petstore/models/pet.cr +++ b/samples/client/petstore/crystal/src/petstore/models/pet.cr @@ -16,23 +16,23 @@ module Petstore class Pet include JSON::Serializable - @[JSON::Field(key: id, type: Int64)] + @[JSON::Field(key: "id", type: Int64)] property id : Int64 - @[JSON::Field(key: category, type: Category)] + @[JSON::Field(key: "category", type: Category)] property category : Category - @[JSON::Field(key: name, type: String)] + @[JSON::Field(key: "name", type: String)] property name : String - @[JSON::Field(key: photoUrls, type: Array(String))] + @[JSON::Field(key: "photoUrls", type: 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) # pet status in the store - @[JSON::Field(key: status, type: String)] + @[JSON::Field(key: "status", type: String)] property status : String class EnumAttributeValidator @@ -60,13 +60,13 @@ module Petstore # Initializes the object # @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 # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties - invalid_properties = Array.new + invalid_properties = Array(String).new if @name.nil? invalid_properties.push("invalid value for \"name\", name cannot be nil.") end diff --git a/samples/client/petstore/crystal/src/petstore/models/tag.cr b/samples/client/petstore/crystal/src/petstore/models/tag.cr index 06e945cfbe0..e9fe7293663 100644 --- a/samples/client/petstore/crystal/src/petstore/models/tag.cr +++ b/samples/client/petstore/crystal/src/petstore/models/tag.cr @@ -16,21 +16,21 @@ module Petstore class Tag include JSON::Serializable - @[JSON::Field(key: id, type: Int64)] + @[JSON::Field(key: "id", type: Int64)] property id : Int64 - @[JSON::Field(key: name, type: String)] + @[JSON::Field(key: "name", type: String)] property name : String # Initializes the object # @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 # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties - invalid_properties = Array.new + invalid_properties = Array(String).new invalid_properties end diff --git a/samples/client/petstore/crystal/src/petstore/models/user.cr b/samples/client/petstore/crystal/src/petstore/models/user.cr index 67910a93943..852159591cf 100644 --- a/samples/client/petstore/crystal/src/petstore/models/user.cr +++ b/samples/client/petstore/crystal/src/petstore/models/user.cr @@ -16,40 +16,40 @@ module Petstore class User include JSON::Serializable - @[JSON::Field(key: id, type: Int64)] + @[JSON::Field(key: "id", type: Int64)] property id : Int64 - @[JSON::Field(key: username, type: String)] + @[JSON::Field(key: "username", type: String)] property username : String - @[JSON::Field(key: firstName, type: String)] + @[JSON::Field(key: "firstName", type: String)] property first_name : String - @[JSON::Field(key: lastName, type: String)] + @[JSON::Field(key: "lastName", type: String)] property last_name : String - @[JSON::Field(key: email, type: String)] + @[JSON::Field(key: "email", type: String)] property email : String - @[JSON::Field(key: password, type: String)] + @[JSON::Field(key: "password", type: String)] property password : String - @[JSON::Field(key: phone, type: String)] + @[JSON::Field(key: "phone", type: String)] property phone : String # User Status - @[JSON::Field(key: userStatus, type: Int32)] + @[JSON::Field(key: "userStatus", type: Int32)] property user_status : Int32 # Initializes the object # @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 # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties - invalid_properties = Array.new + invalid_properties = Array(String).new invalid_properties end