Module: Mapboxkit::Client::Connection

Included in:
Mapboxkit::Client
Defined in:
lib/mapboxkit/connection.rb

Overview

Network layer for API clients.

Defined Under Namespace

Classes: AuthorizationMiddleware

Constant Summary collapse

DEFAULT_REQUEST_CONTENT_TYPE =
'application/json'

Instance Method Summary collapse

Instance Method Details

#connectionObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/mapboxkit/connection.rb', line 45

def connection
  @connection ||= \
    Faraday.new(url: config.url, headers: { 'User-Agent' => config.user_agent }) do |faraday|
      faraday.use(AuthorizationMiddleware, config.access_token)

      faraday.request(:json)

      faraday.request(:multipart, flat_encode: true)

      faraday.response(:logger) if ENV['VERBOSE'] == '1'

      faraday.response(:json, content_type: %r{^application/(vnd\..+\+)?json$})

      faraday.response(:raise_error)

      faraday.adapter(Faraday.default_adapter)
    end
end

#delete(url, params, **kwargs) ⇒ Object



31
32
33
# File 'lib/mapboxkit/connection.rb', line 31

def delete(url, params, **kwargs)
  request(:delete, url, params, **kwargs)
end

#get(url, params = {}) ⇒ Object



13
14
15
16
17
# File 'lib/mapboxkit/connection.rb', line 13

def get(url, params = {})
  response = connection.get(url, params, content_type: nil)

  response.body
end

#patch(url, params, **kwargs) ⇒ Object



27
28
29
# File 'lib/mapboxkit/connection.rb', line 27

def patch(url, params, **kwargs)
  request(:patch, url, params, **kwargs)
end

#post(url, params, **kwargs) ⇒ Object



19
20
21
# File 'lib/mapboxkit/connection.rb', line 19

def post(url, params, **kwargs)
  request(:post, url, params, **kwargs)
end

#put(url, params, **kwargs) ⇒ Object



23
24
25
# File 'lib/mapboxkit/connection.rb', line 23

def put(url, params, **kwargs)
  request(:put, url, params, **kwargs)
end

#request(method, url, params, content_type: DEFAULT_REQUEST_CONTENT_TYPE) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/mapboxkit/connection.rb', line 35

def request(method, url, params, content_type: DEFAULT_REQUEST_CONTENT_TYPE)
  response = connection.public_send(method, url) do |req|
    req.headers[Faraday::CONTENT_TYPE] = content_type

    req.body = params
  end

  response.body
end