github.com/phrase/openapi@v0.0.0-20240514140800-49e8a106740e/openapi-generator/templates/ruby-client/api_client.mustache (about)

     1  require 'date'
     2  require 'json'
     3  require 'logger'
     4  require 'tempfile'
     5  {{^isFaraday}}
     6  require 'typhoeus'
     7  {{/isFaraday}}
     8  {{#isFaraday}}
     9  require 'faraday'
    10  {{/isFaraday}}
    11  
    12  module {{moduleName}}
    13    class ApiClient
    14      # The Configuration object holding settings to be used in the API client.
    15      attr_accessor :config
    16  
    17      # Defines the headers to be used in HTTP requests of all API calls by default.
    18      #
    19      # @return [Hash]
    20      attr_accessor :default_headers
    21  
    22      # Initializes the ApiClient
    23      # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
    24      def initialize(config = Configuration.default)
    25        @config = config
    26        @user_agent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/#{VERSION}/ruby{{/httpUserAgent}}"
    27        @default_headers = {
    28          'Content-Type' => 'application/json',
    29          'User-Agent' => @user_agent
    30        }
    31      end
    32  
    33      def self.default
    34        @@default ||= ApiClient.new
    35      end
    36  
    37  {{^isFaraday}}
    38  {{> api_client_typhoeus_partial}}
    39  {{/isFaraday}}
    40  {{#isFaraday}}
    41  {{> api_client_faraday_partial}}
    42  {{/isFaraday}}
    43      # Check if the given MIME is a JSON MIME.
    44      # JSON MIME examples:
    45      #   application/json
    46      #   application/json; charset=UTF8
    47      #   APPLICATION/JSON
    48      #   */*
    49      # @param [String] mime MIME
    50      # @return [Boolean] True if the MIME is application/json
    51      def json_mime?(mime)
    52        (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
    53      end
    54  
    55      # Deserialize the response to the given return type.
    56      #
    57      # @param [Response] response HTTP response
    58      # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
    59      def deserialize(response, return_type)
    60        body = response.body
    61  
    62        # handle file downloading - return the File instance processed in request callbacks
    63        # note that response body is empty when the file is written in chunks in request on_body callback
    64        return @tempfile if return_type == 'File'
    65  
    66        return nil if body.nil? || body.empty?
    67  
    68        # return response body directly for String return type
    69        return body if return_type == 'String'
    70  
    71        # ensuring a default content type
    72        content_type = response.headers['Content-Type'] || 'application/json'
    73  
    74        fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
    75  
    76        begin
    77          data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
    78        rescue JSON::ParserError => e
    79          if %w(String Date DateTime).include?(return_type)
    80            data = body
    81          else
    82            raise e
    83          end
    84        end
    85  
    86        convert_to_type data, return_type
    87      end
    88  
    89      # Convert data to the given return type.
    90      # @param [Object] data Data to be converted
    91      # @param [String] return_type Return type
    92      # @return [Mixed] Data in a particular type
    93      def convert_to_type(data, return_type)
    94        return nil if data.nil?
    95        case return_type
    96        when 'String'
    97          data.to_s
    98        when 'Integer'
    99          data.to_i
   100        when 'Float'
   101          data.to_f
   102        when 'Boolean'
   103          data == true
   104        when 'DateTime'
   105          # parse date time (expecting ISO 8601 format)
   106          DateTime.parse data
   107        when 'Date'
   108          # parse date time (expecting ISO 8601 format)
   109          Date.parse data
   110        when 'Object'
   111          # generic object (usually a Hash), return directly
   112          data
   113        when /\AArray<(.+)>\z/
   114          # e.g. Array<Pet>
   115          sub_type = $1
   116          data.map { |item| convert_to_type(item, sub_type) }
   117        when /\AHash\<String, (.+)\>\z/
   118          # e.g. Hash<String, Integer>
   119          sub_type = $1
   120          {}.tap do |hash|
   121            data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
   122          end
   123        else
   124          # models, e.g. Pet
   125          {{moduleName}}.const_get(return_type).build_from_hash(data)
   126        end
   127      end
   128  
   129      # Save response body into a file in (the defined) temporary folder, using the filename
   130      # from the "Content-Disposition" header if provided, otherwise a random filename.
   131      # The response body is written to the file in chunks in order to handle files which
   132      # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
   133      # process can use.
   134      #
   135      # @see Configuration#temp_folder_path
   136      def download_file(request)
   137        tempfile = nil
   138        encoding = nil
   139        request.on_headers do |response|
   140          content_disposition = response.headers['Content-Disposition']
   141          if content_disposition && content_disposition =~ /filename=/i
   142            filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
   143            prefix = sanitize_filename(filename)
   144          else
   145            prefix = 'download-'
   146          end
   147          prefix = prefix + '-' unless prefix.end_with?('-')
   148          encoding = response.body.encoding
   149          tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
   150          @tempfile = tempfile
   151        end
   152        request.on_body do |chunk|
   153          chunk.force_encoding(encoding)
   154          tempfile.write(chunk)
   155        end
   156        request.on_complete do |response|
   157          if tempfile
   158            tempfile.close
   159            @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
   160                                "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
   161                                "will be deleted automatically with GC. It's also recommended to delete the temp file "\
   162                                "explicitly with `tempfile.delete`"
   163          end
   164        end
   165      end
   166  
   167      # Sanitize filename by removing path.
   168      # e.g. ../../sun.gif becomes sun.gif
   169      #
   170      # @param [String] filename the filename to be sanitized
   171      # @return [String] the sanitized filename
   172      def sanitize_filename(filename)
   173        filename.gsub(/.*[\/\\]/, '')
   174      end
   175  
   176      def build_request_url(path)
   177        # Add leading and trailing slashes to path
   178        path = "/#{path}".gsub(/\/+/, '/')
   179        @config.base_url + path
   180      end
   181  
   182      # Update hearder and query params based on authentication settings.
   183      #
   184      # @param [Hash] header_params Header parameters
   185      # @param [Hash] query_params Query parameters
   186      # @param [String] auth_names Authentication scheme name
   187      def update_params_for_auth!(header_params, query_params, auth_names)
   188        Array(auth_names).each do |auth_name|
   189          auth_setting = @config.auth_settings[auth_name]
   190          next unless auth_setting
   191          case auth_setting[:in]
   192          when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
   193          when 'query'  then query_params[auth_setting[:key]] = auth_setting[:value]
   194          else fail ArgumentError, 'Authentication token must be in `query` of `header`'
   195          end
   196        end
   197      end
   198  
   199      # Sets user agent in HTTP header
   200      #
   201      # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
   202      def user_agent=(user_agent)
   203        @user_agent = user_agent
   204        @default_headers['User-Agent'] = @user_agent
   205      end
   206  
   207      # Return Accept header based on an array of accepts provided.
   208      # @param [Array] accepts array for Accept
   209      # @return [String] the Accept header (e.g. application/json)
   210      def select_header_accept(accepts)
   211        return nil if accepts.nil? || accepts.empty?
   212        # use JSON when present, otherwise use all of the provided
   213        json_accept = accepts.find { |s| json_mime?(s) }
   214        json_accept || accepts.join(',')
   215      end
   216  
   217      # Return Content-Type header based on an array of content types provided.
   218      # @param [Array] content_types array for Content-Type
   219      # @return [String] the Content-Type header  (e.g. application/json)
   220      def select_header_content_type(content_types)
   221        # use application/json by default
   222        return 'application/json' if content_types.nil? || content_types.empty?
   223        # use JSON when present, otherwise use the first one
   224        json_content_type = content_types.find { |s| json_mime?(s) }
   225        json_content_type || content_types.first
   226      end
   227  
   228      # Convert object (array, hash, object, etc) to JSON string.
   229      # @param [Object] model object to be converted into JSON string
   230      # @return [String] JSON string representation of the object
   231      def object_to_http_body(model)
   232        return model if model.nil? || model.is_a?(String)
   233        local_body = nil
   234        if model.is_a?(Array)
   235          local_body = model.map { |m| object_to_hash(m) }
   236        else
   237          local_body = object_to_hash(model)
   238        end
   239        local_body.to_json
   240      end
   241  
   242      # Convert object(non-array) to hash.
   243      # @param [Object] obj object to be converted into JSON string
   244      # @return [String] JSON string representation of the object
   245      def object_to_hash(obj)
   246        if obj.respond_to?(:to_hash)
   247          obj.to_hash
   248        else
   249          obj
   250        end
   251      end
   252  
   253      # Build parameter value according to the given collection format.
   254      # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
   255      def build_collection_param(param, collection_format)
   256        case collection_format
   257        when :csv
   258          param.join(',')
   259        when :ssv
   260          param.join(' ')
   261        when :tsv
   262          param.join("\t")
   263        when :pipes
   264          param.join('|')
   265        when :multi
   266          # return the array directly as typhoeus will handle it as expected
   267          param
   268        else
   269          fail "unknown collection format: #{collection_format.inspect}"
   270        end
   271      end
   272    end
   273  end