elixir-maru / maru

Elixir RESTful Framework
https://maru.readme.io
BSD 3-Clause "New" or "Revised" License
1.32k stars 84 forks source link

Allow reading parsed params in after-route plug #92

Closed aiwilliams closed 6 years ago

aiwilliams commented 6 years ago

Given the following Maru 0.12.5 setup in a Phoenix 1.3.0 project:

defmodule MyApp.Web.Router do
  use MyApp.Web, :router

  pipeline :my_api do
  end

  scope "/api" do
    pipe_through :my_api
    forward "/", MyAPI
  end
end
defmodule MyAPI.Authenticate do
  use Maru.Middleware

  def call(conn, _opts) do
    conn.params[:app_id]
    conn
  end
end

defmodule MyAPI do
  use Maru.Router, make_plug: true
  plug MyAPI.Authenticate
  mount MyAPI.Resources
end

defmodule MyAPI.Resources do
  use Maru.Router

  params do
    requires :app_id, type: Integer
    requires :id, type: Integer
  end
  get "/:app_id/resources/:id" do
    ...
  end
end

The middleware is unable to read the :app_id and :id params when a request is made to get "/:app_id/resources/:id". My expectation is that because plug MyAPI.Authenticate is not defined in a before block, the plug will run after routing the request, which leads me to think I should be able to read the params after they are parsed, but before the get block is called.

How can I read the endpoint params in a plug invoked before the endpoint code?

falood commented 6 years ago

Hi @aiwilliams I think it's really hard to get params within the middleware. Because the params is per endpoint variable, the params parser won't be run before the request reach the endpoint logic. I'm sorry I think we have to match the conn.path_info to get :app_id and :id manually.

aiwilliams commented 6 years ago

Thank you for your reply. I did use the path info because it was the only approach I could see as well.