Chedy2149
Chedy2149

Reputation: 3051

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

Upvotes: 6

Views: 748

Answers (1)

michalmuskala
michalmuskala

Reputation: 11278

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

Upvotes: 17

Related Questions