lib/MailchimpMarketing/api_client.rb



=begin
#Mailchimp Marketing API

#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)

OpenAPI spec version: 3.0.36
Contact: apihelp@mailchimp.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.4.12

=end

require 'base64'
require 'json'
require 'excon'

module MailchimpMarketing
  class ApiClient
    def initialize(config = {})
      @host = "https://server.api.mailchimp.com/3.0"
      @user_agent = "Swagger-Codegen/#{VERSION}/ruby"
      set_config(config)
    end

    def self.default
      @@default ||= ApiClient.new
    end

    def get_server_from_api_key(api_key = '')
      begin
        split = api_key.split('-')
        server = 'invalid-server'
        if split.length == 2
          server = split[1]
        end
        server
      rescue
        ""
      end
    end

    def set_config(config = {})
      @api_key = config[:api_key] || ''
      @is_basic_auth = @api_key.to_s.strip.empty? == false

      @access_token = config[:access_token] || ''
      @is_oauth = @access_token.to_s.strip.empty? == false

      # If using Basic auth and no server is provided,
      # attempt to extract it from the api_key directy.
      @server = config[:server] || 'invalid-server'
      if @server == 'invalid-server' && @is_basic_auth
        @server = get_server_from_api_key(@api_key)
      end
    end

    def call_api(http_method, path, opts = {})
      headers = {'Content-Type' => "application/json"}
      headers[:Authorization] = "Basic #{encoded_basic_token(@api_key)}" if @is_basic_auth
      headers[:Authorization] = "Bearer #@access_token" if @is_oauth

      host = @server.length > 0 ? @host.sub('server', @server) : @host
      conn = Excon.new(host + path, :headers => headers, :read_timeout => 120, :write_timeout => 120)

      res = nil
      case http_method.to_sym.downcase
      when :post, :put, :patch, :delete
        res = conn.request(:method => http_method, :body => opts[:body])
      when :get
        res = conn.get(:query => opts[:query_params])
      end

      data = nil
      data = JSON.parse(res.body) if res.status == 200
      data = "success" if res.status == 204

      if (!data)
        fail ApiError.new(:status => res.status, :response_body => res.body)
      end

      return data
    end

    # Convert object (array, hash, object, etc) to JSON string.
    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.
    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.
    def build_collection_param(param, collection_format)
      case collection_format
      when :csv
        param.join(',')
      when :ssv
        param.join(' ')
      when :tsv
        param.join("\t")
      when :pipes
        param.join('|')
      when :multi
        param
      else
        fail "unknown collection format: #{collection_format.inspect}"
      end
    end

   private

     # Build base64 encoded token for basic auth.
     def encoded_basic_token(api_key)
       Base64.urlsafe_encode64("user:#{api_key}")
     end
  end
end