-
Notifications
You must be signed in to change notification settings - Fork 74
Better environment value interface #656
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nlarew
wants to merge
4
commits into
main
Choose a base branch
from
better-env
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import { expectType, expectError } from "jest-tsd"; | ||
import { getEnv } from "./getEnv"; | ||
|
||
const originalEnv = process.env; | ||
|
||
beforeEach(() => { | ||
process.env = { ...originalEnv }; | ||
}); | ||
|
||
afterEach(() => { | ||
process.env = originalEnv; | ||
}); | ||
|
||
test("required env vars are strings", () => { | ||
process.env.TEST_ENV_VAR = "test"; | ||
const env = getEnv({ required: ["TEST_ENV_VAR"] }); | ||
expectType<string>(env.TEST_ENV_VAR); | ||
}); | ||
|
||
test("optional env vars with string defaults are strings", () => { | ||
process.env.TEST_ENV_VAR = "test"; | ||
const env = getEnv({ | ||
optional: { TEST_ENV_VAR: "default", TEST_ENV_VAR_2: "default" }, | ||
}); | ||
expectType<string>(env.TEST_ENV_VAR); | ||
expectType<string>(env.TEST_ENV_VAR_2); | ||
}); | ||
|
||
test("optional env vars with undefined defaults are strings or undefined", () => { | ||
process.env.TEST_ENV_VAR = "test"; | ||
const env = getEnv({ | ||
optional: { TEST_ENV_VAR: "default", UNDEFINED_TEST_ENV_VAR: undefined }, | ||
}); | ||
expectType<string>(env.TEST_ENV_VAR); | ||
expectType<string | undefined>(env.UNDEFINED_TEST_ENV_VAR); | ||
}); | ||
|
||
test("accessing an unspecified env var is a type error", () => { | ||
expectError(getEnv({}).FOO); | ||
}); | ||
|
||
test("mixed env vars are the correct type", () => { | ||
process.env.TEST_ENV_VAR = "test"; | ||
process.env.TEST_ENV_VAR_2 = "test"; | ||
const env = getEnv({ | ||
required: ["TEST_ENV_VAR"], | ||
optional: { | ||
TEST_ENV_VAR_2: "default", | ||
TEST_ENV_VAR_3: "default", | ||
TEST_ENV_VAR_4: undefined, | ||
}, | ||
}); | ||
expectType<string>(env.TEST_ENV_VAR); | ||
expectType<string>(env.TEST_ENV_VAR_2); | ||
expectType<string>(env.TEST_ENV_VAR_3); | ||
expectType<string | undefined>(env.TEST_ENV_VAR_4); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
import { expectTypeTestsToPassAsync } from "jest-tsd"; | ||
import { getEnv } from "./getEnv"; | ||
|
||
describe("getEnv", () => { | ||
const ORIGINAL_ENV = process.env; | ||
|
||
beforeEach(() => { | ||
jest.resetModules(); | ||
process.env = { ...ORIGINAL_ENV }; | ||
}); | ||
|
||
afterAll(() => { | ||
process.env = ORIGINAL_ENV; | ||
}); | ||
|
||
it("does not produce static type errors", async () => { | ||
await expectTypeTestsToPassAsync(__filename); | ||
}); | ||
|
||
it("returns required env vars that are defined", () => { | ||
process.env.TEST_ENV_VAR = "test"; | ||
const env = getEnv({ required: ["TEST_ENV_VAR"] }); | ||
expect(env).toEqual({ TEST_ENV_VAR: "test" }); | ||
}); | ||
|
||
it("throws an error if a required env var is not defined", () => { | ||
process.env.TEST_ENV_VAR = "test"; | ||
expect(() => | ||
getEnv({ | ||
required: ["TEST_ENV_VAR", "MISSING_ENV_VAR", "MISSING_ENV_VAR_2"], | ||
}) | ||
).toThrow( | ||
"Missing required environment variables:\n - MISSING_ENV_VAR\n - MISSING_ENV_VAR_2" | ||
); | ||
}); | ||
|
||
it("returns optional env vars that are defined", () => { | ||
process.env.TEST_ENV_VAR = "test"; | ||
process.env.TEST_ENV_VAR_2 = "test"; | ||
const env = getEnv({ | ||
optional: { TEST_ENV_VAR: "default", TEST_ENV_VAR_2: "default" }, | ||
}); | ||
expect(env).toEqual({ TEST_ENV_VAR: "test", TEST_ENV_VAR_2: "test" }); | ||
}); | ||
|
||
it("returns default values for optional env vars that don't exist", () => { | ||
process.env.TEST_ENV_VAR = "test"; | ||
const env = getEnv({ | ||
optional: { TEST_ENV_VAR: "default", UNDEFINED_TEST_ENV_VAR: "default" }, | ||
}); | ||
expect(env).toEqual({ | ||
TEST_ENV_VAR: "test", | ||
UNDEFINED_TEST_ENV_VAR: "default", | ||
}); | ||
}); | ||
|
||
it("can default to a string or undefined", () => { | ||
process.env.TEST_ENV_VAR = "test"; | ||
const env = getEnv({ | ||
optional: { | ||
TEST_ENV_VAR: "default", | ||
TEST_ENV_VAR_2: undefined, | ||
UNDEFINED_TEST_ENV_VAR: "default", | ||
}, | ||
}); | ||
expect(env).toEqual({ | ||
TEST_ENV_VAR: "test", | ||
TEST_ENV_VAR_2: undefined, | ||
UNDEFINED_TEST_ENV_VAR: "default", | ||
}); | ||
}); | ||
|
||
it("works with a mix of required and optional env vars", () => { | ||
process.env.TEST_ENV_VAR = "test"; | ||
process.env.TEST_ENV_VAR_2 = "test"; | ||
const env = getEnv({ | ||
required: ["TEST_ENV_VAR"], | ||
optional: { | ||
TEST_ENV_VAR_2: "default", | ||
UNDEFINED_TEST_ENV_VAR: "default", | ||
}, | ||
}); | ||
expect(env).toEqual({ | ||
TEST_ENV_VAR: "test", | ||
TEST_ENV_VAR_2: "test", | ||
UNDEFINED_TEST_ENV_VAR: "default", | ||
}); | ||
}); | ||
|
||
it("returns an empty object if no env vars are requested", () => { | ||
const env = getEnv({}); | ||
expect(env).toEqual({}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
interface GetEnvArgs< | ||
R extends string, | ||
O extends Record<string, string | undefined> | ||
> { | ||
/** | ||
A list of environment variables that are required. | ||
If any of these are missing, an error will be thrown. | ||
*/ | ||
required?: readonly R[]; | ||
/** | ||
An object of environment variables that are optional. | ||
If any of these are missing, they will default to the value provided. | ||
*/ | ||
optional?: O; | ||
} | ||
|
||
// Helper type to determine the type of an optional env var based on its default value | ||
type OptionalEnvType<T extends string | undefined> = T extends undefined | ||
? string | undefined | ||
: string; | ||
|
||
type EnvFromArgs< | ||
R extends string, | ||
O extends Record<string, string | undefined> | ||
> = { | ||
[K in R]: string; | ||
} & { | ||
[K in keyof O]: OptionalEnvType<O[K]>; | ||
}; | ||
|
||
export function getEnv< | ||
R extends string = never, | ||
O extends Record<string, string | undefined> = Record<never, never> | ||
>({ required, optional }: GetEnvArgs<R, O>): EnvFromArgs<R, O> { | ||
const env = { ...optional }; | ||
const missingRequired: string[] = []; | ||
if (required) { | ||
required.forEach((key) => { | ||
env[key] = process.env[key]; | ||
if (!env[key]) { | ||
missingRequired.push(key); | ||
} | ||
}); | ||
} | ||
if (missingRequired.length > 0) { | ||
throw new Error( | ||
`Missing required environment variables:\n${missingRequired | ||
.map((r) => ` - ${r}`) | ||
.join("\n")}` | ||
); | ||
} | ||
for (const key in optional) { | ||
env[key] = process.env[key] ?? optional[key]; | ||
} | ||
return env as EnvFromArgs<R, O>; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,4 @@ | ||
{ | ||
"extends": "./tsconfig.json", | ||
"exclude": ["**/*.test.ts", "test/**/*.ts"] | ||
"exclude": ["**/*.test.ts", "**/*.test-d.ts", "test/**/*.ts"] | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.