@nestjs/config
Version:
Nest - modern, fast, powerful node.js web framework (@config)
192 lines (191 loc) • 7.38 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 get from 'es-toolkit/compat/get';
import has from 'es-toolkit/compat/has';
import set from 'es-toolkit/compat/set';
import fs from 'fs';
import { Subject } from 'rxjs';
import { CONFIGURATION_TOKEN, VALIDATED_ENV_PROPNAME, } from './config.constants.js';
import { getDefaultParser } from './utils/index.js';
/**
* @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;
this.cache = {};
this._changes$ = new Subject();
this._skipProcessEnv = false;
this._isCacheEnabled = false;
this.envFilePaths = [];
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 validatedEnvValue = this.getFromValidatedEnv(propertyPath);
if (!isUndefined(validatedEnvValue)) {
return validatedEnvValue;
}
const defaultValue = this.isGetOptionsObject(defaultValueOrOptions) &&
!options
? undefined
: defaultValueOrOptions;
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);
set(this.internalConfig, propertyPath, value);
if (typeof propertyPath === 'string') {
process.env[propertyPath] = String(value);
this.updateInterpolatedEnv(propertyPath, String(value));
}
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.
* @param paths
*/
setEnvFilePaths(paths) {
this.envFilePaths = paths;
}
/**
* Sets parser from `config.module.ts`.
* @param parser
*/
setParser(parser) {
this.parser = parser;
}
getFromCache(propertyPath, defaultValue) {
const cachedValue = get(this.cache, propertyPath);
return isUndefined(cachedValue)
? defaultValue
: cachedValue;
}
getFromValidatedEnv(propertyPath) {
const validatedEnvValue = get(this.internalConfig[VALIDATED_ENV_PROPNAME], propertyPath);
return validatedEnvValue;
}
getFromProcessEnv(propertyPath, defaultValue) {
if (this.isCacheEnabled &&
has(this.cache, propertyPath)) {
const cachedValue = this.getFromCache(propertyPath, defaultValue);
return !isUndefined(cachedValue) ? cachedValue : defaultValue;
}
const processValue = get(process.env, propertyPath);
this.setInCacheIfDefined(propertyPath, processValue);
return processValue;
}
getFromInternalConfig(propertyPath) {
const internalValue = get(this.internalConfig, propertyPath);
return internalValue;
}
setInCacheIfDefined(propertyPath, value) {
if (typeof value === 'undefined') {
return;
}
set(this.cache, propertyPath, value);
}
isGetOptionsObject(options) {
return options && options?.infer && Object.keys(options).length === 1;
}
updateInterpolatedEnv(propertyPath, value) {
let config = {};
for (const envFilePath of this.envFilePaths) {
if (fs.existsSync(envFilePath)) {
config = Object.assign(this.parser(fs.readFileSync(envFilePath)), config);
}
}
const escapedKey = propertyPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`\\$\\{${escapedKey}\\}|\\$${escapedKey}(?!\\w)`, 'g');
for (const [k, v] of Object.entries(config)) {
if (typeof v === 'string') {
const updated = v.replace(regex, () => value);
if (updated !== v) {
process.env[k] = updated;
}
}
}
}
};
ConfigService = __decorate([
Injectable(),
__param(0, Optional()),
__param(0, Inject(CONFIGURATION_TOKEN)),
__metadata("design:paramtypes", [Object])
], ConfigService);
export { ConfigService };