Module: PMP::Connection

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

Constant Summary collapse

ALLOWED_CONNECTION_OPTIONS =
[
  :headers,
  :url,
  :params,
  :request,
  :ssl,
  :proxy
].freeze

Instance Method Summary collapse

Instance Method Details

#add_request_auth(opts, faraday) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/pmp/connection.rb', line 34

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



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/pmp/connection.rb', line 18

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

    add_request_auth(options, faraday)

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

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

    faraday.response :logger if options[:debug]

    faraday.adapter options[:adapter]
  end
end

#process_options(opts = {}) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/pmp/connection.rb', line 42

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