Class: WavixApi::Client

Inherits:
Object
  • Object
show all
Includes:
HTTPMethods
Defined in:
lib/wavix_api.rb

Constant Summary

Constants included from HTTPMethods

HTTPMethods::CONTENT_TYPES, HTTPMethods::DEFAULT_HEADERS, HTTPMethods::FILE_NAMES

Instance Method Summary collapse

Methods included from HTTPMethods

#filename, #request

Constructor Details

#initialize(host:, api_key:) ⇒ Client

Returns a new instance of Client.



101
102
103
104
# File 'lib/wavix_api.rb', line 101

def initialize(host:, api_key:)
  @host = host.empty? ? DEFAULT_HOST : host
  @api_key = api_key
end

Instance Method Details

#delete(path, params: {}) ⇒ Object



114
115
116
# File 'lib/wavix_api.rb', line 114

def delete(path, params: {})
  request('DELETE', path, params: params)
end

#download(path, headers: {}, params: {}, save_path: nil) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/wavix_api.rb', line 132

def download(path, headers: {}, params: {}, save_path: nil)
  if save_path
    dirname = File.dirname(save_path)
    dir_parts = dirname.split(%r{[/\\]}).reject(&:empty?)

    (1..dir_parts.size).each do |n|
      dir = dir_parts[0...n].join('/')
      Dir.mkdir("/#{dir}") unless Dir.exist?("/#{dir}")
    end
  end

  response = request('GET', path, params: params, headers: headers)

  return response if save_path.nil? || !response.success? || response.filename.nil?

  filename = if CONTENT_TYPES.keys.find { |el| save_path.include?(".#{el}") }
               save_path
             else
               "#{save_path}/#{response.filename}"
             end

  File.open(filename, 'wb') { |f| f.write response.body }
  response
end

#get(path, params: {}, headers: {}) ⇒ Object



106
107
108
# File 'lib/wavix_api.rb', line 106

def get(path, params: {}, headers: {})
  request('GET', path, params: params, headers: HTTPMethods::DEFAULT_HEADERS.merge(headers))
end

#patch(path, body: {}, params: {}) ⇒ Object



110
111
112
# File 'lib/wavix_api.rb', line 110

def patch(path, body: {}, params: {})
  request('PATCH', path, params: params, body: body.to_json)
end

#post(path, body: {}, params: {}, with_file: false, headers: { 'Content-Type' => 'application/json' }) ⇒ Object



122
123
124
125
126
127
128
129
130
# File 'lib/wavix_api.rb', line 122

def post(path, body: {}, params: {}, with_file: false,
         headers: { 'Content-Type' => 'application/json' })
  body = body.to_json unless with_file
  headers['Content-Type'] = 'multipart/form-data' if with_file

  request('POST', path, params: params, body: body, headers: headers) do |builder|
    builder.request :multipart if with_file
  end
end

#put(path, body: {}, params: {}) ⇒ Object



118
119
120
# File 'lib/wavix_api.rb', line 118

def put(path, body: {}, params: {})
  request('PUT', path, params: params, body: body.to_json)
end