Sha256: d52913639113a01d9d08f3511ada365dc88e15191d8cfb6e1682449eb3a535ac

Contents?: true

Size: 1.89 KB

Versions: 1

Compression:

Stored size: 1.89 KB

Contents

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.use FaradayMiddleware::FollowRedirects
        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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hyperclient-0.5.0 lib/hyperclient/entry_point.rb