Module: TelphinApi::API

Defined in:
lib/telphin_api/api.rb

Overview

A low-level module which handles the requests to Telphin API and returns their results as mashes.

It uses Faraday with middleware underneath the hood.

Class Method Summary collapse

Class Method Details

.call(full_method, args = {}, token = nil) ⇒ Hashie::Mash

API method call.

Parameters:

  • full_method (String)

    A full name of the method.

  • args (Hash) (defaults to: {})

    Method arguments.

  • token (String) (defaults to: nil)

    The access token.

Returns:

  • (Hashie::Mash)

    Mashed server response.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/telphin_api/api.rb', line 12

def call(full_method, args = {}, token = nil)
  namespace = full_method.first
  action = full_method.last

  http_method = args.delete(:http_method)
  http_method ||= :get

  user_id = args.delete(:user_id)
  extension_number = args.delete(:extension_number)

  url_options = args.delete(:url_options)
  url_options ||= []
  url = [namespace, user_id, extension_number, action].concat(url_options).join('/')

  flat_arguments = Utils.flatten_arguments(args)
  flat_arguments = flat_arguments.to_json.to_s if [:post, :put].include? http_method

  connection(url: TelphinApi.site, token: token, method: http_method).send(http_method, url, flat_arguments).body
end

.connection(options = {}) ⇒ Faraday::Connection

Faraday connection.

Parameters:

  • options (Hash) (defaults to: {})

    Connection options.

Options Hash (options):

  • :url (String)

    Connection URL (either full or just prefix).

  • :token (String)

    OAuth2 access token (not used if omitted).

Returns:

  • (Faraday::Connection)

    Created connection.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/telphin_api/api.rb', line 37

def connection(options = {})
  url = options.delete(:url)
  token = options.delete(:token)
  method = options.delete(:method)

  Faraday.new(url, TelphinApi.faraday_options) do |builder|
    builder.headers['Authorization'] = "Bearer #{token}"
    builder.headers['Content-Type'] = 'application/json' if [:post, :put].include? method

    builder.request :multipart
    builder.request :url_encoded
    builder.request :retry, TelphinApi.max_retries

    builder.response :telphin_logger
    builder.response :mashify
    builder.response :multi_json, preserve_raw: true

    builder.adapter TelphinApi.adapter
  end
end