我需要在我的web/router.ex
文件中定义两个管道,如下所示:
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
您可以清楚地看到
:api
管道中的步骤在:restricted_api
管道中重复。有没有办法在
:api
管道中重用:restricted_api
管道?我在考虑类似于继承的东西:
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
最佳答案
pipeline
宏创建一个功能插件。因此,它可以在其他管道中使用,例如任何其他带有plug :pipeline
的插头。在提供的示例中:
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