Module: WavixApi::HTTPMethods

Included in:
Client
Defined in:
lib/wavix_api.rb

Defined Under Namespace

Classes: Response

Constant Summary collapse

DEFAULT_HEADERS =
{ 'Content-Type' => 'application/json' }.freeze
CONTENT_TYPES =
{
  'jpeg' => 'image/jpeg',
  'jpg' => 'image/jpeg',
  'gif' => 'image/gif',
  'png' => 'image/png',
  'pdf' => 'application/pdf',
  'bmp' => 'image/bmp',
  'tiff' => 'image/tiff',
  'doc' => 'application/msword',
  'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'dib' => 'image/dib',
  'amr' => 'audio/amr',
  '3g' => 'audio/3gpp',
  'wav' => 'audio/wav',
  'wave' => 'audio/wav',
  'mp3' => 'audio/mpeg',
  'aac' => 'audio/aac',
  'gcp' => 'audio/gcp',
  'midi' => 'audio/midi',
  'midp' => 'audio/midi'
}.freeze
FILE_NAMES =
%i[attachment paper invoice].freeze

Instance Method Summary collapse

Instance Method Details

#filename(response_headers, path) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
# File 'lib/wavix_api.rb', line 83

def filename(response_headers, path)
  file_by_disposition = response_headers['content-disposition']&.match(/filename="(.+)"/)

  return file_by_disposition[1] if file_by_disposition

  content_type = CONTENT_TYPES.key(response_headers[:content_type])

  return unless content_type

  "#{FILE_NAMES.find { |el| path.include?(el) }}_#{Time.now.to_i}.#{content_type}"
end

#request(method, path, params: {}, body: nil, headers: {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/wavix_api.rb', line 45

def request(method, path, params: {}, body: nil, headers: {})
  connection = Faraday.new(
    url: "https://#{@host}",
    params: { appid: @api_key },
    headers: DEFAULT_HEADERS.merge(headers)
  ) do |builder|
    yield(builder) if block_given?

    builder.use FollowRedirectsMiddleware
    builder.adapter Faraday.default_adapter
  end

  response =
    if %w[GET DELETE].index(method)
      connection.send(method.downcase, path, params)
    else
      connection.send(method.downcase, path) do |request|
        (params || {}).each { |k, v| request.params[k] = v }
        request.body = body if body
      end
    end

  parsed_body = begin
    JSON.parse(response.body)
  rescue JSON::ParserError
    {}
  end

  Response.new(
    response.status,
    response.reason_phrase,
    response.body,
    parsed_body,
    response.success?,
    filename(response.env.response_headers, path)
  )
end