Module: GRApiManager::BodyParser

Defined in:
lib/gr_api_manager.rb

Overview


BodyParser — detects Content-Type and returns an appropriate parsed result.

Supported formats: application/json -> Hash (symbolized keys) multipart/form-data -> Hash + :_files key (FilePayload objects) application/octet-stream -> :_raw_binary (FilePayload) image/* / application/pdf etc. -> :_raw_binary (FilePayload) text/plain -> :_raw_text (String) application/x-www-form-urlencoded-> Hash (Sinatra already handles this)

Constant Summary collapse

BINARY_MIME_PREFIXES =
%w[
  image/ video/ audio/ application/pdf application/msword
  application/vnd. application/zip application/x-tar
  application/x-rar application/octet-stream
].freeze

Class Method Summary collapse

Class Method Details

.binary_content_type?(ct) ⇒ Boolean

Returns:

  • (Boolean)


250
251
252
# File 'lib/gr_api_manager.rb', line 250

def self.binary_content_type?(ct)
  BINARY_MIME_PREFIXES.any? { |prefix| ct.start_with?(prefix) }
end

.ext_for(content_type) ⇒ Object

Maps common MIME types to file extensions for unnamed raw uploads.



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/gr_api_manager.rb', line 255

def self.ext_for(content_type)
  {
    'image/jpeg'          => '.jpg',
    'image/png'           => '.png',
    'image/gif'           => '.gif',
    'image/webp'          => '.webp',
    'image/svg+xml'       => '.svg',
    'image/bmp'           => '.bmp',
    'video/mp4'           => '.mp4',
    'video/webm'          => '.webm',
    'audio/mpeg'          => '.mp3',
    'audio/wav'           => '.wav',
    'application/pdf'     => '.pdf',
    'application/msword'  => '.doc',
    'application/zip'     => '.zip',
    'application/x-tar'   => '.tar',
    'application/octet-stream' => '.bin'
  }.fetch(content_type, '.bin')
end

.parse(request) ⇒ Object

Returns a Hash of parsed body values. Special keys injected into the result hash:

:_files        => { field_name => FilePayload }  (multipart)
:_raw_binary   => FilePayload                    (raw binary body)
:_raw_text     => String                         (plain-text body)


153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/gr_api_manager.rb', line 153

def self.parse(request)
  content_type = (request.content_type || '').split(';').first.strip.downcase

  case content_type
  when 'application/json'
    parse_json(request)

  when 'multipart/form-data'
    parse_multipart(request)

  when 'application/x-www-form-urlencoded'
    # Sinatra already exposes these in `params` — nothing extra to do.
    {}

  when 'text/plain'
    text = request.body.read.to_s.force_encoding(Encoding::UTF_8)
    { _raw_text: text }

  else
    # Treat anything else that looks binary as a raw binary upload.
    if binary_content_type?(content_type)
      parse_raw_binary(request, content_type)
    else
      # Last resort: try JSON, silently fall back to empty hash.
      parse_json(request) rescue {}
    end
  end
end

.parse_json(request) ⇒ Object



185
186
187
188
189
190
191
# File 'lib/gr_api_manager.rb', line 185

def self.parse_json(request)
  body = request.body.read.to_s
  return {} if body.strip.empty?
  JSON.parse(body, symbolize_names: true)
rescue JSON::ParserError => e
  raise ArgumentError, "Invalid JSON body: #{e.message}"
end

.parse_multipart(request) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/gr_api_manager.rb', line 193

def self.parse_multipart(request)
  result = {}
  files  = {}

  request.params.each do |key, value|
    sym = key.to_sym

    if value.is_a?(Hash) && value.key?(:tempfile)
      # Rack multipart file upload hash
      files[sym] = FilePayload.new(
        tempfile:     value[:tempfile],
        filename:     value[:filename] || key,
        content_type: value[:type] || 'application/octet-stream'
      )
    elsif value.is_a?(Array)
      # Multiple file inputs with the same name
      files[sym] = value.map do |v|
        if v.is_a?(Hash) && v.key?(:tempfile)
          FilePayload.new(
            tempfile:     v[:tempfile],
            filename:     v[:filename] || key,
            content_type: v[:type] || 'application/octet-stream'
          )
        else
          v
        end
      end
    else
      result[sym] = value
    end
  end

  result[:_files] = files unless files.empty?
  result
end

.parse_raw_binary(request, content_type) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/gr_api_manager.rb', line 229

def self.parse_raw_binary(request, content_type)
  raw = request.body.read
  return {} if raw.nil? || raw.empty?

  # Try to derive a filename from the Content-Disposition header, if any.
  disposition = request.env['HTTP_CONTENT_DISPOSITION'] || ''
  filename    = disposition[/filename="?([^";]+)"?/, 1] || "upload#{ext_for(content_type)}"

  # Wrap the raw bytes in a StringIO so FilePayload can rewind/read it.
  io = StringIO.new(raw.force_encoding(Encoding::BINARY))
  io.define_singleton_method(:size) { raw.bytesize }

  payload = FilePayload.new(
    tempfile:     io,
    filename:     filename,
    content_type: content_type
  )

  { _raw_binary: payload }
end