-
Notifications
You must be signed in to change notification settings - Fork 37
/
entry_point.rb
59 lines (54 loc) · 1.83 KB
/
entry_point.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
require 'hyperclient/link'
require 'faraday_middleware'
require_relative '../faraday/connection'
module Hyperclient
# Public: The EntryPoint is the main public API for Hyperclient. It is used to
# initialize an API client and setup the configuration.
#
# Examples
#
# client = Hyperclient::EntryPoint.new('http://my.api.org')
#
class EntryPoint < Link
extend Forwardable
# Public: Delegates common methods to be used with the Faraday connection.
def_delegators :connection, :basic_auth, :digest_auth, :token_auth, :headers, :headers=, :params, :params=
# Public: Initializes an EntryPoint.
#
# url - A String with the entry point of your API.
def initialize(url)
@link = {'href' => url}
@entry_point = self
end
# Public: A Faraday connection to use as a HTTP client.
#
# Returns a Faraday::Connection.
def connection
@connection ||= Faraday.new(url, {headers: default_headers}, &default_faraday_block)
end
private
# Internal: Returns a block to initialize the Faraday connection. The
# default block includes a middleware to encode requests as JSON, a
# response middleware to parse JSON responses and sets the adapter as
# NetHttp.
#
# These middleware can always be changed by accessing the Faraday
# connection.
#
# Returns a block.
def default_faraday_block
lambda do |faraday|
faraday.request :json
faraday.response :json, content_type: /\bjson$/
faraday.adapter :net_http
end
end
# Internal: Returns the default headers to initialize the Faraday connection.
# The default headers et the Content-Type and Accept to application/json.
#
# Returns a Hash.
def default_headers
{'Content-Type' => 'application/json', 'Accept' => 'application/json'}
end
end
end