bdunagan

fill the void - bdunagan

25 Sep 2020
Rails Tip: How to Insert Middleware First

During the first iteration of our cloud monitoring service, we deployed software that sent malformed data to it, so we needed to correct the data on the server, as the data came in. The JSON itself was misconstructed for certain objects, so we needed to fix the issue before Rails parsed it.

In application.rb, I added the following line to ensure our middleware was called before anything else, including Rack and Rails middleware:

module RailsApp
  class Application < Rails::Application
    # Insert custom middleware before everything else to rewrite JSON POSTs.

    # What did not work:
    # config.middleware.insert_before ActionDispatch::ParamsParser, "FixJsonParseError"
    # config.middleware.insert_before ActionDispatch::ShowExceptions, "FixJsonParseError"
    # config.middleware.use "FixJsonParseError"

    # What did work:
    config.middleware.insert_before 0, "FixJsonParseError"
  end
end
Previous LinkedIn Twitter GitHub Email Next