Skip to content

Commit ad35676

Browse files
committed
Add getOptionalEnvVar function
Also add tests for it and `getRequiredEnvParam`
1 parent d75645b commit ad35676

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

‎src/util.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,35 @@ test("allowed API versions", async (t) => {
252252
);
253253
});
254254

255+
test("getRequiredEnvParam - gets environment variables", (t) => {
256+
process.env.SOME_UNIT_TEST_VAR = "foo";
257+
const result = util.getRequiredEnvParam("SOME_UNIT_TEST_VAR");
258+
t.is(result, "foo");
259+
});
260+
261+
test("getRequiredEnvParam - throws if an environment variable isn't set", (t) => {
262+
t.throws(() => util.getRequiredEnvParam("SOME_UNIT_TEST_VAR"));
263+
});
264+
265+
test("getOptionalEnvVar - gets environment variables", (t) => {
266+
process.env.SOME_UNIT_TEST_VAR = "foo";
267+
const result = util.getOptionalEnvVar("SOME_UNIT_TEST_VAR");
268+
t.is(result, "foo");
269+
});
270+
271+
test("getOptionalEnvVar - gets undefined for empty environment variables", (t) => {
272+
process.env.SOME_UNIT_TEST_VAR = "";
273+
const result = util.getOptionalEnvVar("SOME_UNIT_TEST_VAR");
274+
t.is(result, undefined);
275+
});
276+
277+
test("getOptionalEnvVar - doesn't throw for undefined environment variables", (t) => {
278+
t.notThrows(() => {
279+
const result = util.getOptionalEnvVar("SOME_UNIT_TEST_VAR");
280+
t.is(result, undefined);
281+
});
282+
});
283+
255284
test("doesDirectoryExist", async (t) => {
256285
// Returns false if no file/dir of this name exists
257286
t.false(util.doesDirectoryExist("non-existent-file.txt"));

‎src/util.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,17 @@ export function getRequiredEnvParam(paramName: string): string {
673673
return value;
674674
}
675675

676+
/**
677+
* Get an environment variable, but return `undefined` if it is not set or empty.
678+
*/
679+
export function getOptionalEnvVar(paramName: string): string | undefined {
680+
const value = process.env[paramName];
681+
if (value?.trim().length === 0) {
682+
return undefined;
683+
}
684+
return value;
685+
}
686+
676687
export class HTTPError extends Error {
677688
public status: number;
678689

0 commit comments

Comments
 (0)