Module: PMP::Connection

Included in:
CollectionDocument, Credential
Defined in:
lib/pmp/connection.rb

Constant Summary collapse

ALLOWED_CONNECTION_OPTIONS =
[
  :headers,
  :url,
  :params,
  :request,
  :adapter,
  :ssl,
  :oauth_token,
  :token_type,
  :basic_auth,
  :user,
  :password,
  :debug
].freeze

Instance Method Summary collapse

Instance Method Details

#add_request_auth(opts, faraday) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/pmp/connection.rb', line 40

def add_request_auth(opts, faraday)
  if opts[:basic_auth] && opts[:user] && opts[:password]
    faraday.request :basic_auth, opts[:user], opts[:password]
  elsif opts[:oauth_token]
    faraday.request :authorization, opts[:token_type], opts[:oauth_token]
  end
end

#connection(options = {}) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/pmp/connection.rb', line 24

def connection(options={})
  opts = process_options(options)
  Faraday::Connection.new(opts) do |faraday|

    add_request_auth(opts, faraday)

    [:multipart, :url_encoded].each{|mw| faraday.request(mw) }

    [:mashify, :json, :raise_error].each{|mw| faraday.response(mw) }

    faraday.response :logger if opts[:debug]

    faraday.adapter opts[:adapter]
  end
end

#process_options(opts = {}) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/pmp/connection.rb', line 48

def process_options(opts={})
  headers = opts.delete(:headers) || {}
  options = {
    :headers => {
      # generic http headers
      'User-Agent'   => opts[:user_agent],
      'Accept'       => "application/vnd.pmp.collection.doc+json",
      'Content-Type' => "application/vnd.pmp.collection.doc+json"
    },
    :ssl => {:verify => false},
    :url => opts[:endpoint]
  }.merge(opts)
  options[:headers] = options[:headers].merge(headers)

  # clean out any that don't belong
  options.select{|k,v| ALLOWED_CONNECTION_OPTIONS.include?(k.to_sym)}
end