New to elixir here - looking for help for the best approach to simple data transformations.
I have a config file that I need to transform slightly into a slightly different format to fit a service call. In essence, it looks like this:
defmodule AppConfig do
@enforce_keys [:username, :endpoints]
defstruct username: "",
password: "",
endpoints: "",
stacktrace: false,
show_sensitive_data_on_connection_error: false,
pool_size: 10,
database: ""
end
defmodule DatabaseConfig do
alias DatabaseUserConfig
@type t() :: %__MODULE__{
name: String.t(),
users: DatabaseUserConfig.t(),
options: any()
}
@enforce_keys [:name]
defstruct [:name, :users, :options]
end
defmodule DatabaseUserConfig do
@type t() :: %__MODULE__{
username: String.t(),
passwd: String.t(),
}
@enforce_keys [:username]
defstruct [:username, :passwd]
end
I need to translate AppConfig
into DatabaseConfig
. Ideally, I’d like to do this in a way so that if I change options, I don’t need to redo this function.
Looking at other libraries, it appears as if the normal way to do this would be to create new
function for DatabaseConfig and pass AppConfig as an argument, then inside that function I’d manually assign each property:
def new(app_config) do
%DatabaseConfig{ name: app_config.database, users: [%User{name: app_config.name, password: app_config.password], options: %{...}]
end
If I filled out options manually, every time I changed the options format in one place or the other, I’d have to redo this function (and any tests with this of course). Is there a way to do the formatting that I know that I need to do, and pass through everything else?