Skip to content

English__Data Sources__Environment

Ramirez Vargas, José Pablo edited this page Nov 7, 2024 · 3 revisions

Environment Data Source

The Environment data source is just a specialization of the Dictionary data source. This data source only allows filtering by using a prefix and the hierarchy separator is double underscores (__) because all operating systems allow the underscore in environment variable names, but not all allow others, such as the dictioary's default value :.

This data source makes the use of the prefix mandatory, and if none is specified, it will be OPT_.

How To Use the Environment Data Source

As with all other data sources, there is a specialized addEnvironment() method in the configuration builder that assists with this job. This function defines two parameters in one overload:

addEnvironment<NewT extends Record<string, any>>(
    env: Record<string, ConfigurationValue> | (() => Promise<Record<string, ConfigurationValue>>),
    prefix?: string
): IBuilder<MergeResult<T, NewT>>;
  1. The environment object, or a function that returns the environment object.
  2. Optional prefix. If not specified, it will be OPT_.

The first one is the main data parameter. As with all other data sources, it may take the environment object directly or it may take a function that returns the environment object. The function approach is the recommended approach when doing any form of conditional configuration if obtaining the environment object will incur in potentially-wasted CPU cycles or RAM.

The second parameter is used to define the prefix the environment variable names must have at the beginning of their names in order to be able to contribute to the final configuration object. It is not possible to add environment data sources that do not use a prefix because it would mean that all environment variables of the host operating system will be imported, resulting most of the time in wasted RAM, clutter in the final configuration object, and even unintentional reveals of potentially secret data.

Data Requirements

Since this is a specialization of the Dictionary data source, all of the data requirements of this ancestor apply here too. Furthermore, hierarchy must be specified with the double underscore (__) and the use of a prefix is mandatory.

Ways to Circumvent This Data Source's Restrictions

If for any reason you have the need to circumvent any of the data restrictions imposed by this data source, feel free to use a dictionary data source in its place. By using the base data source you will be free to set the hierarchy separator, make the prefix optional or even use the predicate function option the Dictionary data source provides for property filtering.