@nestjs/config
Version:
Configuration for NestJS: load .env files and custom configuration, validate it at startup, and read it through an injectable ConfigService.
278 lines (277 loc) • 11.6 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { Inject, Injectable, Optional } from '@nestjs/common';
import { isUndefined } from '@nestjs/common/utils/shared.utils.js';
import { Subject } from 'rxjs';
import { CONFIGURATION_TOKEN, VALIDATED_ENV_PROPNAME, } from './config.constants.js';
import { getDefaultParser } from './utils/index.js';
import { getProperty, setProperty } from './utils/property-path.util.js';
import { readEnvFiles } from './utils/read-env-files.util.js';
// Same syntax as in dotenv-expand: $KEY, ${KEY}, ${KEY:-default},
// ${KEY:+alternative} (also without ":") and \$ for literal $. Nested defaults
// (${A:-${B}}) are not supported
const ENV_REFERENCE_REGEX = /\\\$|\$\{([^{}:+-]+)(?:(:?[-+])([^{}]*))?\}|\$([A-Za-z_]\w*)/g;
// Longest value a variable may get when "set" expands it again. Without a
// limit, a chain of variables that each reference the previous one twice
// doubles in size at every step. A "NAME=value" string of this size can no
// longer be passed to a child process on Linux (MAX_ARG_STRLEN)
const MAX_EXPANDED_LENGTH = 128 * 1024;
/**
* @publicApi
*/
let ConfigService = class ConfigService {
set isCacheEnabled(value) {
this._isCacheEnabled = value;
}
get isCacheEnabled() {
return this._isCacheEnabled;
}
set skipProcessEnv(value) {
this._skipProcessEnv = value;
}
get skipProcessEnv() {
return this._skipProcessEnv;
}
constructor(internalConfig = {}) {
this.internalConfig = internalConfig;
// Keyed by the property path as it was passed to "get"
this.cache = new Map();
this._changes$ = new Subject();
this._skipProcessEnv = false;
this._isCacheEnabled = false;
this.envFilePaths = [];
this.envFileConfig = {};
this.predefinedEnv = new Map();
// Keys passed to "set", which keep their value when a variable they
// reference changes
this.explicitlySetKeys = new Set();
this.parser = getDefaultParser();
}
/**
* Returns a stream of configuration changes.
* Each event contains the attribute path, the old value and the new value.
*/
get changes$() {
return this._changes$.asObservable();
}
/**
* Get a configuration value (either custom configuration or process environment variable)
* based on property path (you can use dot notation to traverse nested object, e.g. "database.host").
* It returns a default value if the key does not exist.
* @param propertyPath
* @param defaultValueOrOptions
*/
get(propertyPath, defaultValueOrOptions, options) {
const internalValue = this.getFromInternalConfig(propertyPath);
if (!isUndefined(internalValue)) {
return internalValue;
}
const defaultValue = this.isGetOptionsObject(defaultValueOrOptions) &&
!options
? undefined
: defaultValueOrOptions;
const validatedEnvValue = this.validatedEnv?.resolve(propertyPath);
if (validatedEnvValue?.found) {
// Variable that validation mapped to "undefined" is not looked up in
// process.env, which may still hold its raw value
return isUndefined(validatedEnvValue.value)
? defaultValue
: validatedEnvValue.value;
}
if (!this._skipProcessEnv) {
const processEnvValue = this.getFromProcessEnv(propertyPath, defaultValue);
if (!isUndefined(processEnvValue)) {
return processEnvValue;
}
}
return defaultValue;
}
/**
* Get a configuration value (either custom configuration or process environment variable)
* based on property path (you can use dot notation to traverse nested object, e.g. "database.host").
* It returns a default value if the key does not exist.
* If the default value is undefined an exception will be thrown.
* @param propertyPath
* @param defaultValueOrOptions
*/
getOrThrow(propertyPath, defaultValueOrOptions, options) {
// @ts-expect-error Bypass method overloads
const value = this.get(propertyPath, defaultValueOrOptions, options);
if (isUndefined(value)) {
throw new TypeError(`Configuration key "${propertyPath.toString()}" does not exist`);
}
return value;
}
/**
* Sets a configuration value based on property path.
* @param propertyPath
* @param value
*/
set(propertyPath, value) {
const oldValue = this.get(propertyPath);
// Computed first, as it throws if a variable would grow too long
const interpolatedEnv = typeof propertyPath === 'string'
? this.getInterpolatedEnv(propertyPath, String(value))
: new Map();
setProperty(this.internalConfig, propertyPath, value);
if (typeof propertyPath === 'string') {
this.explicitlySetKeys.add(propertyPath);
this.setEnv(propertyPath, String(value));
// Not predefined for a later "forRoot" (e.g. app bootstrapped again)
this.loadedEnv?.set(propertyPath, String(value));
interpolatedEnv.forEach((updated, key) => this.setInterpolatedEnv(key, updated));
}
if (this.isCacheEnabled) {
this.setInCacheIfDefined(propertyPath, value);
}
this._changes$.next({
path: propertyPath,
oldValue,
newValue: value,
});
}
/**
* Sets env file paths from `config.module.ts` to parse.
* The files are read once, when this method is called.
* @param paths
* @deprecated `ConfigModule.forRoot()` passes the variables it loaded instead.
*/
setEnvFilePaths(paths) {
this.envFilePaths = paths;
this.envFileConfig = readEnvFiles(paths, this.parser);
}
/**
* Sets parser from `config.module.ts`.
* @param parser
* @deprecated `ConfigModule.forRoot()` passes the variables it loaded instead.
*/
setParser(parser) {
this.parser = parser;
this.envFileConfig = readEnvFiles(this.envFilePaths, parser);
}
setEnvFileConfig(envFileConfig) {
this.envFileConfig = envFileConfig;
}
setExpansionEnv(expansionEnv) {
this.expansionEnv = expansionEnv;
}
getFromCache(propertyPath, defaultValue) {
const cachedValue = this.cache.get(propertyPath);
return isUndefined(cachedValue)
? defaultValue
: cachedValue;
}
get validatedEnv() {
return this.internalConfig[VALIDATED_ENV_PROPNAME];
}
getFromProcessEnv(propertyPath, defaultValue) {
if (this.isCacheEnabled && this.cache.has(propertyPath)) {
const cachedValue = this.getFromCache(propertyPath, defaultValue);
return !isUndefined(cachedValue) ? cachedValue : defaultValue;
}
const processValue = getProperty(process.env, propertyPath);
if (this.isCacheEnabled) {
this.setInCacheIfDefined(propertyPath, processValue);
}
return processValue;
}
getFromInternalConfig(propertyPath) {
const internalValue = getProperty(this.internalConfig, propertyPath);
return internalValue;
}
setInCacheIfDefined(propertyPath, value) {
if (typeof value === 'undefined') {
return;
}
this.cache.set(propertyPath, value);
}
isGetOptionsObject(options) {
return options && options?.infer && Object.keys(options).length === 1;
}
setPredefinedEnv(predefinedEnv, loadedEnv) {
this.predefinedEnv = predefinedEnv;
this.loadedEnv = loadedEnv;
}
setEnv(key, value) {
process.env[key] = value;
if (this.expansionEnv) {
this.expansionEnv[key] = value;
}
}
expandReferences(key, value, lookup) {
// Current values are inserted as is (unlike dotenv-expand, "$" inside of
// them is not expanded again)
return value.replace(ENV_REFERENCE_REGEX, (match, bracedKey, operator = '', alternative = '', plainKey) => {
if (match === '\\$') {
return '$';
}
const name = bracedKey ?? plainKey;
const current = name === key ? undefined : lookup(name);
if (operator.endsWith('+')) {
return current ? alternative : '';
}
return current || alternative;
});
}
/**
* Returns the env file variables whose expanded value changes when
* "propertyPath" is set to "value", with their new value
*/
getInterpolatedEnv(propertyPath, value) {
const env = this.expansionEnv ?? process.env;
const updates = new Map([[propertyPath, value]]);
const lookup = (name) => updates.has(name) ? updates.get(name) : env[name];
for (const [k, v] of Object.entries(this.envFileConfig)) {
// Value that was in process.env before env file was loaded wins, same
// as in dotenv-expand on startup. So does a value passed to "set" (by
// this or an earlier call), which is what "get" returns
const predefined = this.predefinedEnv.get(k);
if (typeof v !== 'string' ||
k === propertyPath ||
this.explicitlySetKeys.has(k) ||
(predefined && predefined !== v)) {
continue;
}
const references = [...v.matchAll(ENV_REFERENCE_REGEX)].map(([, key, , , plainKey]) => key ?? plainKey);
if (!references.some(ref => updates.has(ref))) {
continue;
}
const updated = this.expandReferences(k, v, lookup);
if (updated === process.env[k]) {
continue;
}
if (updated.length > MAX_EXPANDED_LENGTH) {
throw new Error(`Environment variable "${k}" is too long after variable expansion`);
}
updates.set(k, updated);
}
updates.delete(propertyPath);
return updates;
}
setInterpolatedEnv(key, value) {
this.setEnv(key, value);
// Not predefined for a later "forRoot" (e.g. app bootstrapped again)
this.loadedEnv?.set(key, value);
if (this.isCacheEnabled) {
this.setInCacheIfDefined(key, value);
}
this.validatedEnv?.update(key, value);
}
};
ConfigService = __decorate([
Injectable(),
__param(0, Optional()),
__param(0, Inject(CONFIGURATION_TOKEN)),
__metadata("design:paramtypes", [Object])
], ConfigService);
export { ConfigService };