Class: API::APIGuard::ResponseCoercerMiddleware

Inherits:
Grape::Middleware::Base
  • Object
show all
Defined in:
lib/api/api_guard.rb

Overview

Prior to Rack v2.1.x, returning a body of [nil] or [201] worked because the body was coerced to a string. However, this no longer works in Rack v2.1.0+. The Rack spec (github.com/rack/rack/blob/master/SPEC.rdoc#the-body-) says:

The Body must respond to ‘each` and must only yield String values

Because it’s easy to return the wrong body type, this middleware will:

  1. Inspect each element of the body if it is an Array.

  2. Coerce each value to a string if necessary.

  3. Flag a test and development error.

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/api/api_guard.rb', line 218

def call(env)
  response = super(env)

  status = response[0]
  body = response[2]

  return response if Rack::Utils::STATUS_WITH_NO_ENTITY_BODY[status]
  return response unless body.is_a?(Array)

  body.map! do |part|
    if part.is_a?(String)
      part
    else
      err = ArgumentError.new("The response body should be a String, but it is of type #{part.class}")
      Gitlab::ErrorTracking.track_and_raise_for_dev_exception(err)
      part.to_s
    end
  end

  response
end