Skip to content

Global middleware configuration #403

@tanguilp

Description

@tanguilp

Just an idea, I'd be glad to have feedback here: in my apps and libs I often allow configuration options to add Tesla middlewares either globally or for a specific module. For instance:

dev.exs:

config :my_lib, :tesla_middlewares, [Tesla.Middleware.Logger]

config :my_lib, :tesla_middlewares_for_some_module, [Another.Tesla.Middleware]

and then in my code I build the list of middlewares:

my_module.ex:

defp middlewares() do
  [Tesla.Middleware.JSONDecode, Some.Other.Needed.Middleware]
  ++ Application.get_env(:my_lib, :tesla_middlewares_some_domain, [])
  ++ Application.get_env(:my_lib, :tesla_middlewares, [])
end

The global :tesla_middlewares allows applying some interesting things globally:

  • enabling / disabling logging in dev or for debugging in prod
  • setting application ID header to all outbound requests
  • having telemetry for all outbound requests
  • etc.

Now my problem is that when having an app using different libs, one would need to configure the same middlewares for each lib:

config :my_app, :tesla_middlewares, [Tesla.Middleware.Logger]

config :my_lib_1, :tesla_middlewares, [Tesla.Middleware.Logger]

config :my_lib_2, :tesla_middlewares, [Tesla.Middleware.Logger]

config :my_lib_3, :tesla_middlewares, [Tesla.Middleware.Logger]

Hence the following idea: couldn't Tesla automatically add middlewares declared using a configuration option (for example: config :tesla, :middlewares) to all clients? Unless there's already a way of achieving that? This also could be a convention / best practice. What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions