Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse a router pipeline definiton in another pipeline definition in phoenix framework?

I need to define two pipelines in my web/router.ex file as follows:

pipeline :api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
end

pipeline :restricted_api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
  plug MyApp.Plugs.EnsureAuthenticated
  plug MyApp.Plugs.EnsureAuthorized
end 

You can clearly see that steps from the :api pipeline are duplicated in the :restricted_api pipeline.

Is there a way to reuse the :api pipeline in the :restricted_api pipeline?

I am thinking about something similar to inheritance:

pipeline :api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
end

pipeline :restricted_api do
  extend :api
  plug MyApp.Plugs.EnsureAuthenticated
  plug MyApp.Plugs.EnsureAuthorized
end
like image 986
Chedy2149 Avatar asked Dec 06 '22 14:12

Chedy2149


1 Answers

The pipeline macro creates a function plug. Therefore it can be used in other pipelines like any other plug with plug :pipeline. In the provided example:

pipeline :api do
  plug :accepts, ["json"]
  plug :fetch_session
  plug MyApp.Plugs.ValidatePayload
end

pipeline :restricted_api do
  plug :api
  plug MyApp.Plugs.EnsureAuthenticated
  plug MyApp.Plugs.EnsureAuthorized
end
like image 121
michalmuskala Avatar answered Jan 07 '23 04:01

michalmuskala