/
config.service.ts
246 lines (225 loc) 路 8.25 KB
/
config.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import { Inject, Injectable, Optional } from '@nestjs/common';
import { isUndefined } from '@nestjs/common/utils/shared.utils';
import { get, has, set } from 'lodash';
import {
CONFIGURATION_TOKEN,
VALIDATED_ENV_PROPNAME,
} from './config.constants';
import { NoInferType, Path, PathValue } from './types';
/**
* `ExcludeUndefinedIf<ExcludeUndefined, T>
*
* If `ExcludeUndefined` is `true`, remove `undefined` from `T`.
* Otherwise, constructs the type `T` with `undefined`.
*/
type ExcludeUndefinedIf<
ExcludeUndefined extends boolean,
T,
> = ExcludeUndefined extends true ? Exclude<T, undefined> : T | undefined;
export interface ConfigGetOptions {
/**
* If present, "get" method will try to automatically
* infer a type of property based on the type argument
* specified at the "ConfigService" class-level (example: ConfigService<Configuration>).
*/
infer: true;
}
type KeyOf<T> = keyof T extends never ? string : keyof T;
@Injectable()
export class ConfigService<
K = Record<string, unknown>,
WasValidated extends boolean = false,
> {
private set isCacheEnabled(value: boolean) {
this._isCacheEnabled = value;
}
private get isCacheEnabled(): boolean {
return this._isCacheEnabled;
}
private readonly cache: Partial<K> = {} as any;
private _isCacheEnabled = false;
constructor(
@Optional()
@Inject(CONFIGURATION_TOKEN)
private readonly internalConfig: Record<string, any> = {},
) {}
/**
* 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").
* @param propertyPath
*/
get<T = any>(propertyPath: KeyOf<K>): ExcludeUndefinedIf<WasValidated, T>;
/**
* 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").
* @param propertyPath
* @param options
*/
get<T = K, P extends Path<T> = any, R = PathValue<T, P>>(
propertyPath: P,
options: ConfigGetOptions,
): ExcludeUndefinedIf<WasValidated, R>;
/**
* 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 defaultValue
*/
get<T = any>(propertyPath: KeyOf<K>, defaultValue: NoInferType<T>): T;
/**
* 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 defaultValue
* @param options
*/
get<T = K, P extends Path<T> = any, R = PathValue<T, P>>(
propertyPath: P,
defaultValue: NoInferType<R>,
options: ConfigGetOptions,
): R;
/**
* 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<T = any>(
propertyPath: KeyOf<K>,
defaultValueOrOptions?: T | ConfigGetOptions,
options?: ConfigGetOptions,
): T | undefined {
const validatedEnvValue = this.getFromValidatedEnv(propertyPath);
if (!isUndefined(validatedEnvValue)) {
return validatedEnvValue;
}
const defaultValue =
this.isGetOptionsObject(defaultValueOrOptions) && !options
? undefined
: defaultValueOrOptions;
const processEnvValue = this.getFromProcessEnv(propertyPath, defaultValue);
if (!isUndefined(processEnvValue)) {
return processEnvValue;
}
const internalValue = this.getFromInternalConfig(propertyPath);
if (!isUndefined(internalValue)) {
return internalValue;
}
return defaultValue as T;
}
/**
* 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").
* @param propertyPath
*/
getOrThrow<T = any>(propertyPath: KeyOf<K>): Exclude<T, undefined>;
/**
* 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").
* @param propertyPath
* @param options
*/
getOrThrow<T = K, P extends Path<T> = any, R = PathValue<T, P>>(
propertyPath: P,
options: ConfigGetOptions,
): Exclude<T, undefined>;
/**
* 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 defaultValue
*/
getOrThrow<T = any>(
propertyPath: KeyOf<K>,
defaultValue: NoInferType<T>,
): Exclude<T, undefined>;
/**
* 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 defaultValue
* @param options
*/
getOrThrow<T = K, P extends Path<T> = any, R = PathValue<T, P>>(
propertyPath: P,
defaultValue: NoInferType<R>,
options: ConfigGetOptions,
): Exclude<R, undefined>;
/**
* 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<T = any>(
propertyPath: KeyOf<K>,
defaultValueOrOptions?: T | ConfigGetOptions,
options?: ConfigGetOptions,
): Exclude<T, undefined> {
// @ts-expect-error Bypass method overloads
const value = this.get(propertyPath, defaultValueOrOptions, options) as
| T
| undefined;
if (isUndefined(value)) {
throw new TypeError(`Configuration key "${propertyPath}" does not exist`);
}
return value as Exclude<T, undefined>;
}
private getFromCache<T = any>(
propertyPath: KeyOf<K>,
defaultValue?: T,
): T | undefined {
const cachedValue = get(this.cache, propertyPath);
return isUndefined(cachedValue)
? defaultValue
: (cachedValue as unknown as T);
}
private getFromValidatedEnv<T = any>(propertyPath: KeyOf<K>): T | undefined {
const validatedEnvValue = get(
this.internalConfig[VALIDATED_ENV_PROPNAME],
propertyPath,
);
return validatedEnvValue as unknown as T;
}
private getFromProcessEnv<T = any>(
propertyPath: KeyOf<K>,
defaultValue: any,
): T | undefined {
if (
this.isCacheEnabled &&
has(this.cache as Record<any, any>, propertyPath)
) {
const cachedValue = this.getFromCache(propertyPath, defaultValue);
return !isUndefined(cachedValue) ? cachedValue : defaultValue;
}
const processValue = get(process.env, propertyPath);
this.setInCacheIfDefined(propertyPath, processValue);
return processValue as unknown as T;
}
private getFromInternalConfig<T = any>(
propertyPath: KeyOf<K>,
): T | undefined {
const internalValue = get(this.internalConfig, propertyPath);
return internalValue;
}
private setInCacheIfDefined(propertyPath: KeyOf<K>, value: any): void {
if (typeof value === 'undefined') {
return;
}
set(this.cache as Record<any, any>, propertyPath, value);
}
private isGetOptionsObject(
options: Record<string, any> | undefined,
): options is ConfigGetOptions {
return options && options?.infer && Object.keys(options).length === 1;
}
}