@nestjs/config
Version:
Configuration for NestJS: load .env files and custom configuration, validate it at startup, and read it through an injectable ConfigService.
54 lines (53 loc) • 2.17 kB
JavaScript
import { getRootKey, hasOwn, resolveProperty } from './property-path.util.js';
const NOT_FOUND = { found: false, value: undefined };
/**
* Validated environment variables served by `ConfigService#get`, one layer
* per `ConfigModule.forRoot()` call. A layer holds the validator's output as
* is, so that the members of a class instance it returns keep working.
*/
export class ValidatedEnv {
constructor() {
this.layers = [];
}
add(values, hiddenKeys, convertedKeys) {
this.layers.push({ values, hiddenKeys, convertedKeys });
}
/**
* Resolves a property path. "found" with an `undefined` value means that
* the validator removed the variable.
*/
resolve(path) {
for (const layer of this.getLayers(path)) {
const result = resolveProperty(layer.values, path);
if (result.found) {
return result;
}
}
return NOT_FOUND;
}
/**
* Replaces the value of a variable that is a string (a value converted by
* validation, e.g. to a number, is not replaced, it isn't validated again).
* The variable name is used as is, never as a path.
*/
update(key, value) {
const layer = this.getLayers(key).find(({ values }) => hasOwn(values, key));
if (layer &&
!Object.isFrozen(layer.values) &&
typeof layer.values[key] === 'string') {
layer.values[key] = value;
}
}
/**
* Returns the layers that may serve a path, in the order they are tried:
* the ones that converted it (the last first), then all of them in the
* order they were added. So a value a validator only passed through (e.g.
* the raw form of a variable another validator converted) doesn't replace a
* converted one.
*/
getLayers(path) {
const visibleLayers = this.layers.filter(({ values, hiddenKeys }) => !hiddenKeys.has(getRootKey(values, path)));
const convertingLayers = visibleLayers.filter(({ values, convertedKeys }) => convertedKeys.has(getRootKey(values, path)));
return [...convertingLayers.reverse(), ...visibleLayers];
}
}