Class: Restforce::Middleware::Multipart

Inherits:
Faraday::Request::UrlEncoded
  • Object
show all
Defined in:
lib/restforce/middleware/multipart.rb

Constant Summary collapse

DEFAULT_BOUNDARY =
"--boundary_string"
JSON_CONTENT_TYPE =
{ "Content-Type" => "application/json" }.freeze

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/restforce/middleware/multipart.rb', line 9

def call(env)
  match_content_type(env) do |params|
    env[:request] ||= {}
    env[:request][:boundary] ||= DEFAULT_BOUNDARY
    env[:request_headers][CONTENT_TYPE] += ";boundary=#{env[:request][:boundary]}"
    env[:body] = create_multipart(env, params)
  end
  @app.call env
end

#create_multipart(env, params) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/restforce/middleware/multipart.rb', line 37

def create_multipart(env, params)
  boundary = env[:request][:boundary]
  parts = []

  # Fields
  parts << Faraday::Parts::Part.new(
    boundary,
    'entity_content',
    params.reject { |k, v| v.respond_to? :content_type }.to_json,
    JSON_CONTENT_TYPE
  )

  # Files
  params.each do |k, v|
    next unless v.respond_to? :content_type

    parts << Faraday::Parts::Part.new(boundary,
                                      k.to_s,
                                      v)
  end

  parts << Faraday::Parts::EpiloguePart.new(boundary)

  body = Faraday::CompositeReadIO.new(parts)
  env[:request_headers]['Content-Length'] = body.length.to_s
  body
end

#has_multipart?(obj) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
30
31
32
33
34
35
# File 'lib/restforce/middleware/multipart.rb', line 27

def has_multipart?(obj)
  # string is an enum in 1.8, returning list of itself
  if obj.respond_to?(:each) && !obj.is_a?(String)
    (obj.respond_to?(:values) ? obj.values : obj).each do |val|
      return true if val.respond_to?(:content_type) || has_multipart?(val)
    end
  end
  false
end

#process_request?(env) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
24
25
# File 'lib/restforce/middleware/multipart.rb', line 19

def process_request?(env)
  type = request_type(env)
  env[:body].respond_to?(:each_key) && !env[:body].empty? && (
    (type.empty? && has_multipart?(env[:body])) ||
    type == self.class.mime_type
  )
end