Skip to content

Commit b91e24c

Browse files
committed
better handling of default-env
1 parent d13c871 commit b91e24c

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

src/shared/cf-env.js

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
"use strict";
22

3+
const pathlib = require("path");
4+
const fs = require("fs");
5+
36
const ENV = Object.freeze({
47
USER: "USER",
58
CF_APP: "VCAP_APPLICATION",
@@ -23,18 +26,23 @@ class CfEnv {
2326
} catch (err) {} // eslint-disable-line no-empty
2427
}
2528

26-
constructor(env = process.env) {
27-
if (env.NODE_ENV !== "production" && env.USE_DEFAULT_ENV) {
28-
try {
29-
const { VCAP_APPLICATION, VCAP_SERVICES } = require(process.cwd() + "/default-env.json");
30-
if (VCAP_APPLICATION && !Object.prototype.hasOwnProperty.call(env, "VCAP_APPLICATION")) {
31-
env.VCAP_APPLICATION = JSON.stringify(VCAP_APPLICATION);
32-
}
33-
if (VCAP_SERVICES && !Object.prototype.hasOwnProperty.call(env, "VCAP_SERVICES")) {
34-
env.VCAP_SERVICES = JSON.stringify(VCAP_SERVICES);
29+
static readDefaultEnv() {
30+
try {
31+
const defaultEnvRaw = fs.readFileSync(pathlib.resolve(process.cwd(), "default-env.json"), "utf8");
32+
return Object.entries(JSON.parse(defaultEnvRaw)).reduce((acc, [key, value]) => {
33+
if (value !== null) {
34+
acc[key] = JSON.stringify(value);
3535
}
36-
} catch (err) {} // eslint-disable-line no-empty
37-
}
36+
return acc;
37+
}, {});
38+
} catch (err) {} // eslint-disable-line no-empty
39+
}
40+
41+
constructor(inputEnv = process.env) {
42+
const env = {
43+
...(inputEnv.NODE_ENV !== "production" && CfEnv.readDefaultEnv()),
44+
...inputEnv,
45+
};
3846

3947
this.isOnCf = env[ENV.USER] === "vcap";
4048
this.cfApp = CfEnv.parseEnvVar(env, ENV.CF_APP) || {};

0 commit comments

Comments
 (0)