Search code examples
rubyrackmiddleware

Combine Rack::Builder and Rack::Cascade


Sorry if this question is a duplication of another question, but i haven't found it yet.

I have some Grape APIs (which are Rack apps) and one of them (the user API) uses a middleware for authentication.

In my config.ru file i combined all APIs to one app via Rack::Cascade. Here's the code:

user_management = Rack::Builder.new {
  use Middleware
  run UserAPI.new
}
app = Rack::Cascade.new [
    user_management,
    ExampleAPI1,
    ExampleAPI2,
    ExampleAPI3
]

The problem is that the middleware is called every time when any of the APIs gets a request.

Does anybody have any advice on how to use the middleware only when the user API gets a request?


Solution

  • The answer to this question is that I had to remove the resources (e.g. resource :user) from the APIs and then use Rack::Builder as follows:

    app = Rack::Builder.new {
        map '/user' do
            use Middleware
            run ExampleAPI1
        end
    
        map '/items' do
            run ExampleAPI2
        end
    
        map '/locations' do
            run ExampleAPI3
        end
    
        map '/reports' do
            run ExampleAPI4
        end
    }
    

    The problem with Rack::Cascade was that it tries every app from top to bottom until it finds the a suitable endpoint