Skip to content

Commit

Permalink
Support supplying bag to read variables from
Browse files Browse the repository at this point in the history
  • Loading branch information
knpwrs committed Jan 19, 2023
1 parent 55c6027 commit d2bf209
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import env from '@knpwrs/envariant';
const DB_URI = env('DB_URI');
// DB_URI is guaranteed to be defined at this point, as long as there is a `DB_URI` environment variable defined.
// If there isn't a `DB_URI` variable defined then `env` will throw and this script will crash.

// There is an optional second parameter that lets you supply an object to read variables from; for
// instance, the `env` parameter in Cloudflare workers:
const ENDPOINT = env('ENDPOINT', env);
```

## Installation
Expand Down
10 changes: 9 additions & 1 deletion src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,13 @@ test('variable defined', () => {
});

test('variable not defined', () => {
expect(() => env(name)).toThrow(`${name} is not defined in process.env!`);
expect(() => env(name)).toThrow(`${name} is not defined in environment!`);
});

test('variable defined in provided bag', () => {
expect(env('foo', { foo: 'bar' })).toBe('bar');
});

test('variable not defined in provided bag', () => {
expect(() => env('foo', {})).toThrow('foo is not defined in environment!');
});
9 changes: 6 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
export default function envariant(name: string): string {
const value = process.env[name];
export default function envariant(
name: string,
bag: Record<string, string | undefined> = process.env,
): string {
const value = bag[name];

if (!value) {
throw new Error(`${name} is not defined in process.env!`);
throw new Error(`${name} is not defined in environment!`);
}

return value;
Expand Down

0 comments on commit d2bf209

Please sign in to comment.