grape icon indicating copy to clipboard operation
grape copied to clipboard

Broken middleware behaviour for reused endpoints

Open etehtsea opened this issue 8 years ago • 5 comments

require 'grape'

class Endpoint < Grape::API
  format :txt

  get(:e) { 'Endpoint was called' }
end

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

  def call(env)
    @app.call(env).tap do |r|
      r.write(' and middleware too')
    end
  end
end

class Protected < Grape::API
  use Middleware

  mount Endpoint
end

class Routes
  def initialize
    @app = Rack::Builder.app do
      map('/n') { run Class.new(Grape::API) { mount Endpoint } }
      map('/o') { run Endpoint }
      map('/p') { run Protected }
    end.freeze
  end

  def call(env)
    @app.call(env)
  end
end

run Routes.new
$  curl localhost:9292/p/e  
Endpoint was called  

$  curl localhost:9292/o/e    
Endpoint was called     

$  curl localhost:9292/n/e    
Endpoint was called

Expected behaviour: Middleware would run in endpoint mounted to /p/e. Actual behaviour: Middleware don't get executed at all.

If I comment out /n/e mapping:

require 'grape'

class Endpoint < Grape::API
  format :txt

  get(:e) { 'Endpoint was called' }
end

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

  def call(env)
    @app.call(env).tap do |r|
      r.write(' and middleware too')
    end
  end
end

class Protected < Grape::API
  use Middleware

  mount Endpoint
end

class Routes
  def initialize
    @app = Rack::Builder.app do
#     map('/n') { run Class.new(Grape::API) { mount Endpoint } }
      map('/o') { run Endpoint }
      map('/p') { run Protected }
    end.freeze
  end

  def call(env)
    @app.call(env)
  end
end

run Routes.new
$  curl localhost:9292/o/e
Endpoint was called and middleware too
$  curl localhost:9292/p/e
Endpoint was called and middleware too

Expected behaviour: Middleware would run in endpoint mounted to /p/e. Actual behaviour: Middleware is affecting mapping where it should not get executed.

etehtsea avatar Apr 11 '17 05:04 etehtsea

You should turn this into a spec next, looks like a bug.

dblock avatar Apr 12 '17 11:04 dblock

This is fixed, right @etehtsea ?

dblock avatar Sep 03 '20 12:09 dblock

@dblock I dunno. I decided to close it as stale because it wasn't caught by anyone else for the whole 3 years.

etehtsea avatar Sep 04 '20 02:09 etehtsea

I'll reopen it, I think it's still a bug until someone can try it out again and turn it into a spec if we don't have one like that. Maybe you? :)

dblock avatar Sep 04 '20 12:09 dblock

@dblock unfortunately not :) I don't use grape anymore (so as Ruby).

etehtsea avatar Sep 05 '20 03:09 etehtsea