Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prioritize env API_FORMAT over Rack::CONTENT_TYPE header #2505

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

trialize
Copy link

As per #2171

Fix the Order of Conditions in fetch_formatter to Correctly Use Custom Formatters

Issue:

In Grape::Middleware::Formatter.fetch_formatter, the current order of conditions causes custom formatters specified in env[Grape::Env::API_FORMAT] to be ignored in favor of the default formatter associated with the Content-Type header.

Original Code:

def fetch_formatter(headers, options)
  api_format = mime_types[headers[Grape::Http::Headers::CONTENT_TYPE]] || env[Grape::Env::API_FORMAT]
  Grape::Formatter.formatter_for(api_format, **options)
end

Problem:

This code prioritizes the Content-Type header over the env[Grape::Env::API_FORMAT]. As a result, even if a custom formatter is explicitly set in the environment, it may be overridden by the default formatter determined by the Content-Type.

Solution:

Swap the order of conditions so that env[Grape::Env::API_FORMAT] takes precedence:

def fetch_formatter(headers, options)
  api_format = env[Grape::Env::API_FORMAT] || mime_types[headers[Grape::Http::Headers::CONTENT_TYPE]]
  Grape::Formatter.formatter_for(api_format, **options)
end

Rationale:

By giving priority to env[Grape::Env::API_FORMAT], we ensure that custom formatters are correctly recognized and applied, allowing for more flexible and accurate response formatting.

Example:

# Define a custom formatter
content_type :raw_json, 'application/json'
formatter :raw_json, ->(object, _env) { object }

# Use the custom formatter within an endpoint
get do
  env['api.format'] = :raw_json
  body <<-HERE
  {
    "glossary": {
      "title": "example glossary",
      "GlossDiv": {
        "title": "S",
        "GlossList": {
          "GlossEntry": {
            "ID": "SGML",
            "SortAs": "SGML",
            "GlossTerm": "Standard Generalized Markup Language",
            "Acronym": "SGML",
            "Abbrev": "ISO 8879:1986",
            "GlossDef": {
              "para": "A meta-markup language, used to create markup languages such as DocBook.",
              "GlossSeeAlso": ["GML", "XML"]
            },
            "GlossSee": "markup"
          }
        }
      }
    }
  }
  HERE
end

Before the Fix:

The custom formatter :raw_json is not applied. Instead, Grape uses its default JSON formatter.

After the Fix:

The custom formatter :raw_json is correctly applied, and the response body is returned exactly as intended.

@grape-bot
Copy link

2 Warnings
⚠️ There're library changes, but not tests. That's OK as long as you're refactoring existing code.
⚠️ Unless you're refactoring existing code or improving documentation, please update CHANGELOG.md.

Here's an example of a CHANGELOG.md entry:

* [#2505](https://github.com/ruby-grape/grape/pull/2505): Prioritize env api_format over rack::content_type header - [@trialize](https://github.com/trialize).

Generated by 🚫 Danger

Copy link
Member

@dblock dblock left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks reasonable.

This needs a test, a CHANGELOG entry, a paragraph in UPGRADING, and some documentation about order of formatters in README, please.

This is a breaking change, but also likely a bug. If no existing tests fail we are good with the above.

I see this test fail.

  1) Grape::API.format :json can be overwritten with an explicit content type
     Failure/Error: expect(last_response.body).to eq({ meaning_of_life: 42 }.to_s)

       expected: #<Encoding:US-ASCII> "{:meaning_of_life=>42}"
            got: #<Encoding:ASCII-8BIT> "\"{:meaning_of_life=>42}\""

       (compared using ==)
     # ./spec/grape/api_spec.rb:4101:in `block (4 levels) in <top (required)>'

Let's understand whether the test is just wrong?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants