4

I'm integrating a 3rd party API, and at one step they post JSON data into our server.

The content type is application/json, but the payload is actually gzipped. Due to the content type, rails is throwing an ActionDispatch::ParamsParser::ParseError exception when trying to parse the data.

I plan to write a rack middleware to catch the exception and try and uncompress the payload, but I only want to do it for that particular action, is there a way to execute the middleware only for specific routes?

Update

I'd already thought about pattern matching the path, but ideally I'd like something that is a little more robust in case paths change in the future.

Update

The issue regarding compression is better approached by matt's comment below, and the routing is answered in another question that this is now marked a duplicate of.

agbodike
  • 1,796
  • 18
  • 27
  • 1
    Wouldn’t it be better to check the `Content-encoding` header of the request, and deal with the compression based on that? (Assuming the 3rd party is including that header, go and give them a (metaphorical) slap if they’re not.) – matt Dec 04 '15 at 21:59
  • Probably, after further investigation that seems like a good approach, and they are sending the `content-encoding` header – agbodike Dec 04 '15 at 22:49
  • @matt I found this: https://gist.github.com/relistan/2109707 which can be used along the lines of your suggestion – agbodike Dec 04 '15 at 23:11

1 Answers1

9

You can easily to do a regex match on the path, and only execute uncompress code when the path matches. In this case, you are not skipping the middleware for all other routes, but processing the check should be very lightweight. Place this in lib/middleware/custom_middleware.rb:

class CustomMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    @req = Rack::Request.new(env)

    if should_use_this?
      # Your custom code goes here.
    end
  end


  def should_use_this?
    @req.path =~ /^matchable_path/ # Replace "matchable_path" with the path in question.
  end

end

Then put the following in your config/environments/production.rb

config.middleware.use "CustomMiddleware"
rlarcombe
  • 2,958
  • 1
  • 17
  • 22
  • 2
    That's a possibility I'd already thought about, but I want something that is a little more robust than simple pattern matching on the path. – agbodike Dec 04 '15 at 20:15