3
votes

My task is to read the JSON file on the Application run and store it in the config. I have gone through https://hexdocs.pm/elixir/master/Config.Provider.html

Now my config provider code is

defmodule JSONConfigProvider do
  @behaviour Config.Provider

  # Let's pass the path to the JSON file as config
  def init(path) when is_binary(path), do: path

  def load(config, path) do
    # We need to start any app we may depend on.
    {:ok, _} = Application.ensure_all_started(:jason)

    json = path |> File.read!() |> Jason.decode!()

    json
  end
end

When I try to run this through iex everything looks fine

JSONConfigProvider.load([existing: :config, app: [:appname]],"file_path")

and the next step is Then when specifying your release, you can specify the provider in the release configuration

I don't have the mix release. Is there any way to store this in the config(dev.ex)?

1

1 Answers

4
votes

My task is to read the JSON file on the Application run and store it in the config.

There is a confusion between application config, and configuration files where this config is [usually] loaded from.

ConfigProvider is used to load configuration from .json file into application config. By default, the application would load .exs configs only, so what you actually need would be to instruct your application to use your new provider to load the configuration from .json.

It does not matter, whether we are talking about releases, or not. Without syntactic sugar, one might load JSON from the file and alter the application config on the fly with Application.put_all_env/2 or Application.put_env/4 for fine tuning.

Releases are different in many ways (it’s out of the scope of this question,) that’s why the documentation suggests altering the releases section of project file. To load it for development, you just do:

defmodule MyApp.Application do
  @moduledoc false
  use Application

  @spec start(Application.app(), Application.restart_type()) ::
        Supervisor.on_start()
  def start(_type, _args) do
    config =
      JSONConfigProvider.load(
        [existing: :config, app: [:my_app]], "file_path")
    Application.put_all_env({:my_app, config}, persistent: true)

    ...