在配置文件中调用Project.Endpoint.static_url()

问题描述 投票:1回答:1

我需要配置OAuth协议,这样做的逻辑位置在/config/dev.exs内,不是吗?

在上面,我配置Endpoint。所以在我的应用程序中,我可以编写Project.Endpoint.static_url()并获得eg。 http://localhost:4000

在配置中获取此值的DRY方法是什么?

config :project, Project.Endpoint,
  http: [port: 4000],
  url: [scheme: "http", host: "localhost", port: 4000]

config :project, authentication: [
    client_id: System.get_env("CLIENT_ID"),
    client_secret: System.get_env("CLIENT_SECRET"),
    site: "https://example.com",
    authorize_url: "/connexion/oauth2/authorize",
    redirect_uri: "http://localhost:4000/oauth/callback"
    # This version fails: Project.Endpoint.static_url/0 is undefined (module Project.Endpoint is not available)
    # redirect_uri: "#{Project.Endpoint.static_url()}/oauth/callback"
  ]

谢谢

elixir phoenix-framework dry
1个回答
1
投票

首先,您应该知道Elixir将在编译时解析配置文件,这意味着在编译应用程序时将评估System.get_env。在编译的代码中,值将是固定的。

Elixir团队正在努力简化此过程,但目前建议的方法是推迟读取环境变量,直到您的应用程序启动。

通常,这可以在启动子项之前在应用程序模块中完成,方法是调用Application.put_env/3-4并输入从System.get_env读取的值。

像Ecto这样的库也提供init回调,允许您挂钩到引导过程以动态配置。见https://hexdocs.pm/ecto/Ecto.Repo.html#module-urls

这也是摆脱重复的地方。毕竟,配置只是Elixir代码,你可以根据你的期望简单地设置其他值:

defmodule Project.Application do
  use Application

  def start(_type, _args) do
    Application.put_env :project, authentication: [
      redirect_uri: "#{Project.Endpoint.static_url()}/oauth/callback",
      ...
    ]

    children = [
      Project.Repo,
      ProjectWeb.Endpoint,
      ...
    ]
    opts = [strategy: :one_for_one, name: Project.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

你也可以混合配置文件和Application.put_env,但是你需要自己合并这些值。

© www.soinside.com 2019 - 2024. All rights reserved.