UNPKG

8.4 kBJavaScriptView Raw
1"use strict";
2var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3 if (k2 === undefined) k2 = k;
4 var desc = Object.getOwnPropertyDescriptor(m, k);
5 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6 desc = { enumerable: true, get: function() { return m[k]; } };
7 }
8 Object.defineProperty(o, k2, desc);
9}) : (function(o, m, k, k2) {
10 if (k2 === undefined) k2 = k;
11 o[k2] = m[k];
12}));
13var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14 Object.defineProperty(o, "default", { enumerable: true, value: v });
15}) : function(o, v) {
16 o["default"] = v;
17});
18var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21 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;
22 return c > 3 && r && Object.defineProperty(target, key, r), r;
23};
24var __importStar = (this && this.__importStar) || function (mod) {
25 if (mod && mod.__esModule) return mod;
26 var result = {};
27 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
28 __setModuleDefault(result, mod);
29 return result;
30};
31var __metadata = (this && this.__metadata) || function (k, v) {
32 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
33};
34var __param = (this && this.__param) || function (paramIndex, decorator) {
35 return function (target, key) { decorator(target, key, paramIndex); }
36};
37var __importDefault = (this && this.__importDefault) || function (mod) {
38 return (mod && mod.__esModule) ? mod : { "default": mod };
39};
40Object.defineProperty(exports, "__esModule", { value: true });
41exports.ConfigService = void 0;
42const common_1 = require("@nestjs/common");
43const shared_utils_1 = require("@nestjs/common/utils/shared.utils");
44const dotenv = __importStar(require("dotenv"));
45const fs_1 = __importDefault(require("fs"));
46const get_1 = __importDefault(require("lodash/get"));
47const has_1 = __importDefault(require("lodash/has"));
48const set_1 = __importDefault(require("lodash/set"));
49const rxjs_1 = require("rxjs");
50const config_constants_1 = require("./config.constants");
51/**
52 * @publicApi
53 */
54let ConfigService = class ConfigService {
55 set isCacheEnabled(value) {
56 this._isCacheEnabled = value;
57 }
58 get isCacheEnabled() {
59 return this._isCacheEnabled;
60 }
61 constructor(internalConfig = {}) {
62 this.internalConfig = internalConfig;
63 this.cache = {};
64 this._changes$ = new rxjs_1.Subject();
65 this._isCacheEnabled = false;
66 this.envFilePaths = [];
67 }
68 /**
69 * Returns a stream of configuration changes.
70 * Each event contains the attribute path, the old value and the new value.
71 */
72 get changes$() {
73 return this._changes$.asObservable();
74 }
75 /**
76 * Get a configuration value (either custom configuration or process environment variable)
77 * based on property path (you can use dot notation to traverse nested object, e.g. "database.host").
78 * It returns a default value if the key does not exist.
79 * @param propertyPath
80 * @param defaultValueOrOptions
81 */
82 get(propertyPath, defaultValueOrOptions, options) {
83 const validatedEnvValue = this.getFromValidatedEnv(propertyPath);
84 if (!(0, shared_utils_1.isUndefined)(validatedEnvValue)) {
85 return validatedEnvValue;
86 }
87 const defaultValue = this.isGetOptionsObject(defaultValueOrOptions) &&
88 !options
89 ? undefined
90 : defaultValueOrOptions;
91 const processEnvValue = this.getFromProcessEnv(propertyPath, defaultValue);
92 if (!(0, shared_utils_1.isUndefined)(processEnvValue)) {
93 return processEnvValue;
94 }
95 const internalValue = this.getFromInternalConfig(propertyPath);
96 if (!(0, shared_utils_1.isUndefined)(internalValue)) {
97 return internalValue;
98 }
99 return defaultValue;
100 }
101 /**
102 * Get a configuration value (either custom configuration or process environment variable)
103 * based on property path (you can use dot notation to traverse nested object, e.g. "database.host").
104 * It returns a default value if the key does not exist.
105 * If the default value is undefined an exception will be thrown.
106 * @param propertyPath
107 * @param defaultValueOrOptions
108 */
109 getOrThrow(propertyPath, defaultValueOrOptions, options) {
110 // @ts-expect-error Bypass method overloads
111 const value = this.get(propertyPath, defaultValueOrOptions, options);
112 if ((0, shared_utils_1.isUndefined)(value)) {
113 throw new TypeError(`Configuration key "${propertyPath.toString()}" does not exist`);
114 }
115 return value;
116 }
117 /**
118 * Sets a configuration value based on property path.
119 * @param propertyPath
120 * @param value
121 */
122 set(propertyPath, value) {
123 const oldValue = this.get(propertyPath);
124 (0, set_1.default)(this.internalConfig, propertyPath, value);
125 if (typeof propertyPath === 'string') {
126 process.env[propertyPath] = String(value);
127 this.updateInterpolatedEnv(propertyPath, String(value));
128 }
129 if (this.isCacheEnabled) {
130 this.setInCacheIfDefined(propertyPath, value);
131 }
132 this._changes$.next({
133 path: propertyPath,
134 oldValue,
135 newValue: value,
136 });
137 }
138 /**
139 * Sets env file paths from `config.module.ts` to parse.
140 * @param paths
141 */
142 setEnvFilePaths(paths) {
143 this.envFilePaths = paths;
144 }
145 getFromCache(propertyPath, defaultValue) {
146 const cachedValue = (0, get_1.default)(this.cache, propertyPath);
147 return (0, shared_utils_1.isUndefined)(cachedValue)
148 ? defaultValue
149 : cachedValue;
150 }
151 getFromValidatedEnv(propertyPath) {
152 const validatedEnvValue = (0, get_1.default)(this.internalConfig[config_constants_1.VALIDATED_ENV_PROPNAME], propertyPath);
153 return validatedEnvValue;
154 }
155 getFromProcessEnv(propertyPath, defaultValue) {
156 if (this.isCacheEnabled &&
157 (0, has_1.default)(this.cache, propertyPath)) {
158 const cachedValue = this.getFromCache(propertyPath, defaultValue);
159 return !(0, shared_utils_1.isUndefined)(cachedValue) ? cachedValue : defaultValue;
160 }
161 const processValue = (0, get_1.default)(process.env, propertyPath);
162 this.setInCacheIfDefined(propertyPath, processValue);
163 return processValue;
164 }
165 getFromInternalConfig(propertyPath) {
166 const internalValue = (0, get_1.default)(this.internalConfig, propertyPath);
167 return internalValue;
168 }
169 setInCacheIfDefined(propertyPath, value) {
170 if (typeof value === 'undefined') {
171 return;
172 }
173 (0, set_1.default)(this.cache, propertyPath, value);
174 }
175 isGetOptionsObject(options) {
176 return options && options?.infer && Object.keys(options).length === 1;
177 }
178 updateInterpolatedEnv(propertyPath, value) {
179 let config = {};
180 for (const envFilePath of this.envFilePaths) {
181 if (fs_1.default.existsSync(envFilePath)) {
182 config = Object.assign(dotenv.parse(fs_1.default.readFileSync(envFilePath)), config);
183 }
184 }
185 const regex = new RegExp(`\\$\\{?${propertyPath}\\}?`, 'g');
186 for (const [k, v] of Object.entries(config)) {
187 if (regex.test(v)) {
188 process.env[k] = v.replace(regex, value);
189 }
190 }
191 }
192};
193exports.ConfigService = ConfigService;
194exports.ConfigService = ConfigService = __decorate([
195 (0, common_1.Injectable)(),
196 __param(0, (0, common_1.Optional)()),
197 __param(0, (0, common_1.Inject)(config_constants_1.CONFIGURATION_TOKEN)),
198 __metadata("design:paramtypes", [Object])
199], ConfigService);