-
Notifications
You must be signed in to change notification settings - Fork 44
/
config.service.ts
349 lines (302 loc) · 8.31 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import { Injectable } from '@nestjs/common';
import * as assert from 'assert';
import * as get from 'lodash.get';
import * as set from 'lodash.set';
import { DotenvConfigOptions, config as dotenv } from 'dotenv';
import * as path from 'path';
import { Glob, sync as globSync } from 'glob';
import { ProxyProperty } from '../decorators/proxy';
export interface ModuleConfig {
[key: string]: any;
}
export interface Config {
[key: string]: ModuleConfig;
}
export type CustomHelper = {
[key: string]: (...args: any[]) => any;
};
export interface ConfigOptions extends Partial<DotenvConfigOptions> {
modifyConfigName?: (name: string) => string;
}
@Injectable()
@ProxyProperty('helpers')
export class ConfigService {
[key: string]: Config | CustomHelper | ((...args: any[]) => any) | any;
private static config: Config;
private readonly helpers: CustomHelper = {};
public static rootPath?: string;
/**
* @deprecated use rootPath instead
*/
public static srcPath?: string;
/**
* @param {Config} config
*/
constructor(config: Config = {}) {
this.bindCustomHelpers(config);
ConfigService.config = config;
}
/**
* Load configuration from file system
* @param glob string
* @param {DotenvOptions} options
* @returns {Promise<any>}
*/
static async load(
glob: string,
options?: ConfigOptions | false,
): Promise<ConfigService> {
const configs = await this.loadConfigAsync(glob, options);
return new ConfigService(configs);
}
/**
* Load config synchronously
* @param {string} glob
* @param {DotenvOptions | false} options
*/
static loadSync(glob: string, options?: ConfigOptions | false) {
const configs = this.loadConfigSync(glob, options);
return new ConfigService(configs);
}
/**
* Get the param or use default
*
* @param {String} key
* @param {any} value default
* @returns {any|undefined}
*/
static get(param: string | string[], value: any = undefined): any {
const configValue = get(ConfigService.config, param);
if (configValue === undefined) {
return value;
}
return configValue;
}
/**
* Get the param or use default
*
* @param param
* @param {any} value default
* @returns {any}
*/
get(param: string | string[], value: any = undefined): any {
return ConfigService.get(param, value);
}
/**
* Set config value at runtime
* @param {string} param
* @param value
* @returns {Config}
*/
set(param: string | string[], value: any = null): Config {
return set(ConfigService.config, param, value);
}
/**
* Check the param exists
*
* @param param
* @returns {boolean}
*/
has(param: string | string[]): boolean {
return get(ConfigService.config, param) !== undefined;
}
/**
* Merge configuration
* @param glob
* @param options
*/
async merge(glob: string, options?: ConfigOptions): Promise<void> {
const config = await ConfigService.loadConfigAsync(glob, options);
Object.keys(config).forEach((configName) => {
ConfigService.config[configName] = config[configName];
});
}
/**
* Merge configuration synchronously
* @param {string} glob
* @param {DotenvOptions} options
* @returns {ConfigService}
*/
mergeSync(glob: string, options?: ConfigOptions): ConfigService {
const config = ConfigService.loadConfigSync(glob, options);
Object.keys(config).forEach((configName) => {
ConfigService.config[configName] = config[configName];
});
return this;
}
/**
* @param {string} name
* @param {CustomHelper} fn
* @returns {ConfigService}
*/
registerHelper(name: string, fn: (...args: any[]) => any): ConfigService {
this.helpers[name] = fn.bind(this);
return this;
}
/**
* @param {string} dir
* @returns {string}
*/
public static root(dir: string = ''): string {
const rootPath =
this.rootPath || this.srcPath || path.resolve(process.cwd());
return path.resolve(rootPath, dir);
}
/**
* @param {string} dir
* @returns {string}
*
* @deprecated use configService.root() instead
*/
public static src(dir: string = ''): string {
console.log(
`\x1b[33m%s\x1b[0m`,
`WARNING: Method 'src' has been deprecated. Please use 'root'`,
);
return this.root(dir);
}
/**
* Resolves and stores sources directory for application.
* @param {string} startPath
* The path for search starting. Can be any path under app sources path.
*/
public static resolveRootPath(startPath: string): typeof ConfigService {
assert.ok(
path.isAbsolute(startPath),
'Start path must be an absolute path.',
);
if (!this.rootPath) {
const root = this.root();
let workingDir = startPath;
let parent = path.dirname(startPath);
while (workingDir !== root && parent !== root && parent !== workingDir) {
workingDir = parent;
parent = path.dirname(workingDir);
}
this.rootPath = workingDir;
this.srcPath = workingDir;
}
return this;
}
/**
* @param startPath
*
* @deprecated use configService.resolveRootPath() instead
*/
public static resolveSrcPath(startPath: string): typeof ConfigService {
console.log(
`\x1b[33m%s\x1b[0m`,
`WARNING: Method 'resolveSrcPath' has been deprecated. Please use 'resolveRootPath'`,
);
return this.resolveRootPath(startPath);
}
/**
* @param {string | string[]} glob
* @param {DotenvOptions | false} options
* @returns {Promise<Config>}
*/
protected static loadConfigAsync(
glob: string,
options?: ConfigOptions | false,
): Promise<Config> {
glob = this.root(glob);
return new Promise((resolve, reject) => {
new Glob(glob, {}, (err, matches) => {
/* istanbul ignore if */
if (err) {
reject(err);
} else {
this.loadEnv(options);
const configs = this.configGraph(
matches,
options && options.modifyConfigName,
);
resolve(configs);
}
});
});
}
/**
* Load config synchronously
* @param {string} glob
* @param {DotenvOptions | false} options
* @returns {Config}
*/
protected static loadConfigSync(
glob: string,
options?: ConfigOptions | false,
): Config {
glob = this.root(glob);
const matches = globSync(glob);
this.loadEnv(options);
return this.configGraph(matches, options && options.modifyConfigName);
}
/**
* Config graph from an array of paths
* @param configPaths
* @param modifyConfigName
* @returns {any}
*/
protected static configGraph(
configPaths: string[],
modifyConfigName?: (name: string) => string,
) {
return configPaths.reduce((configs: Config, file: string) => {
const module = require(file);
const config = module.default || module;
const configName = modifyConfigName
? modifyConfigName(this.getConfigName(file))
: this.getConfigName(file);
configs[configName] = config;
return configs;
}, {});
}
/**
* @param config
* @returns {string}
*/
protected bindCustomHelpers(config) {
return Object.keys(config).reduce((configObj, configName) => {
if (typeof configObj[configName] === 'function') {
const helper = configObj[configName].bind(this);
configObj[configName] = helper;
this.helpers[`_${configName}`] = helper;
}
if (
typeof configObj[configName] === 'object' &&
configObj[configName] !== null
) {
configObj[configName] = this.bindCustomHelpers(configObj[configName]);
}
return configObj;
}, config);
}
/**
* Get config name from a file path
* @param {string} file
* @returns {string}
*/
protected static getConfigName(file: string) {
const ext = path.extname(file);
return path.basename(file, ext);
}
/**
* Loads env variables via dotenv.
* @param {DotenvConfigOptions | false} options
*/
protected static loadEnv(options?: DotenvConfigOptions | false): void {
if (options !== false) {
dotenv(options || ConfigService.defaultDotenvConfig());
}
}
/**
* Default dotenv config point to a .env
* on the cwd path
* @returns {{path: string}}
*/
protected static defaultDotenvConfig() {
return {
path: path.join(process.cwd(), '.env'),
};
}
}