EnvironmentSource
The EnvironmentSource loads configuration assignments from environment variables. By default,
the environment variable name is formed by combining the appName value (passed in the context)
with the dotted property path (from the schema), and converting the whole thing to CONSTANT_CASE.
In the case that a property name at the start of the path has the same name as appName (it is often useful to
encapsulate the app's configurables into a property schema!), the name is truncated to avoid redundancy.
For example, given the app called basics defined in the Getting Started
section, here are some environment variables that would be loaded:
BASICS_DEBUG=true
BASICS_VERBOSE=true
BASICS_CODES=5xx,z10,123
BASICS_SERVER_HOST=localhost
BASICS_SERVER_PORT=8081
BASICS_SERVER_PROTOCOL=https
(If we didn't truncate the redundant name segment, we'd need to use BASICS_BASICS_VERBOSE=true!)
If you don't provide an appName in the context, the environment variables will not have a prefix at all,
which may lead to surprising results if you inadvertently define a property with the same name as a common shell variable.
By default, the EnvironmentSource will load data from process.env. However, it is possible to
pass in an object containing values via a property in the context object passed to Configurator.load(),
by default context.env. (This is used in the examples directory to ensure a consistent environment for demo purposes.)
For example:
const config = await Configurator.load(schema, {
appName: 'basics',
env: {'BASICS_SERVER_HOST': '127.0.0.1'} // normally omit - uses process.env by default
});
Constructor
new EnvironmentSource(options)
| Param | Type | Description |
|---|---|---|
[options] | object | Optional settings |
[options.sequence] | number | Priority number. Defaults to ConfigurationSource.DefaultSequence.ENVIRONMENT (400) |
[options.contextName] | string | Name of context field to load from (default: "env") |
Examples
Basic Usage
import { EnvironmentSource } from '@versionzero/configurator/sources';
// Use default context name ('env') and process.env
const source = new EnvironmentSource();
// Or specify custom context name
const source = new EnvironmentSource({ contextName: 'envVars' });
Complete Example
import { Schema, Configurator } from '@versionzero/configurator';
const schema = new Schema('object')
.property('server', new Schema('object')
.property('host', new Schema('string').default('localhost'))
.property('port', new Schema('number').default(3000))
);
// Uses process.env automatically (EnvironmentSource is included in default sources)
const config = await Configurator.load(schema, {
appName: 'myapp'
});
// Environment variables: MYAPP_SERVER_HOST, MYAPP_SERVER_PORT