4

In Phoenix I have my routes as follow :

  scope "/", ManaWeb do
    pipe_through [:browser, :auth]
    get "/register",  RegistrationController, :new
    post "/register", RegistrationController, :register
  end

However I would like to set a Plug for the last route (POST).

How would I go about that with current tools ?

thodg
  • 1,773
  • 15
  • 24

2 Answers2

9

Another solution would be using the plug directly in the controller

defmodule ManaWeb.RegistrationController do
  # import the post_plug...
  plug :post_plug when action in [:register]

  def register(conn, params) do
    # ...
  end
end
fhdhsni
  • 1,529
  • 1
  • 13
  • 21
  • 1
    I would say this is more elegant than my proposal. Upvoted. – Aleksei Matiushkin Apr 03 '20 at 06:10
  • The pipeline approach is good enough for me, this is very interesting though as il allows setting the plugs in the controller per route. Is this documented somewhere ? – thodg Apr 03 '20 at 15:36
  • @thodg it should be somewhere in the official doc but I read it in the Programming Phoenix book – fhdhsni Apr 04 '20 at 20:33
7

As it is stated in the documentation for Phoenix.Router.pipeline/2

Every time pipe_through/1 is called, the new pipelines are appended to the ones previously given.

That said, this would work:

scope "/", ManaWeb do
  pipe_through [:browser, :auth]
  get "/register",  RegistrationController, :new

  pipe_through :post_plug
  post "/register", RegistrationController, :register
end
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160