UNPKG

3.06 kBJavaScriptView Raw
1'use strict';
2
3
4const configuration = {
5
6
7 /* CONSTANTS */
8 DEVELOPMENT: 'development',
9 PRODUCTION: 'production',
10 TESTING: 'testing',
11 TEST: 'test',
12
13 _initialized: false,
14
15 production: false,
16
17 /**
18 * System environment
19 */
20 env: null,
21
22 /**
23 * Call me once after run
24 */
25 init () {
26 if (!this._initialized) {
27 this.env = process.env.NODE_ENV || this.DEVELOPMENT;
28
29 try {
30 const defaultConfigFile = this._getDefaultConfigFile();
31 if (defaultConfigFile) {
32 this._merge(require(this._getDefaultConfigFile())); // eslint-disable-line
33 }
34
35 const environmentSpecificConfigFile = this._getEnvSpecificConfigFile(this.env);
36 if (environmentSpecificConfigFile) {
37 this._merge(require(environmentSpecificConfigFile)); // eslint-disable-line
38 }
39 } catch (e) {
40 console.error('Can\'t load configuration', e); // eslint-disable-line
41 }
42
43 this._initialized = true;
44 }
45 },
46
47 /**
48 * Returns if is in production mode
49 *
50 * @returns {boolean}
51 */
52 isProduction () {
53 return this.production;
54 },
55
56 /**
57 * Constructs testing DB name for testing pipelines from desired prefix and commit hash if present.
58 * Makes sure that the desired database name does not exceed MongoDB's length limit of database name when
59 * constructing with commit hash.
60 *
61 * @param {string} prefix
62 * @param {string} [commit]
63 * @returns {string}
64 */
65 constructTestingDbName (prefix, commit = null) {
66
67 if (commit && prefix.length > 16) {
68 prefix = prefix.slice(0, 16);
69 }
70
71 return commit
72 ? `${prefix}${commit.slice(0, 16)}`
73 : prefix;
74 },
75
76 /**
77 * Returns environment specific configuration file name
78 *
79 * @param env {string} current environment
80 * @returns {string|null}
81 * @private
82 */
83 _getEnvSpecificConfigFile (env) { // eslint-disable-line
84 return null;
85 },
86
87 /**
88 * Returns default configuration file name
89 *
90 * @returns {string|null}
91 * @private
92 */
93 _getDefaultConfigFile () {
94 return null;
95 },
96
97 /**
98 * Merge configuration files
99 *
100 * @param replaceWith
101 * @param defaults
102 * @private
103 */
104 _merge (replaceWith, defaults) {
105 defaults = defaults || this;
106
107 for (const k in replaceWith) {
108 if (!Object.prototype.hasOwnProperty.call(replaceWith, k)) {
109 continue;
110 }
111 if (typeof replaceWith[k] !== 'object' || replaceWith[k] === null || Array.isArray(replaceWith[k])
112 || typeof defaults[k] !== 'object' || defaults[k] === null) {
113
114 defaults[k] = replaceWith[k];
115 } else {
116 this._merge(replaceWith[k], defaults[k]);
117 }
118 }
119 }
120};
121
122module.exports = configuration;