Skip to content

Commit

Permalink
fix: fallback to process.env when window is not available (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukashass committed Jan 24, 2022
1 parent b16a0d9 commit 6efa912
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
11 changes: 7 additions & 4 deletions src/getEnvConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ export interface EnvConfig {
}

export function getEnvConfig<T extends keyof EnvConfig>(key: keyof EnvConfig): EnvConfig[T] | undefined {
const { env } = window as unknown as { env: EnvConfig };
const config = env || {};

return config[key];
const _window = global.window as unknown as { env?: EnvConfig };
if (_window?.env) {
return _window.env[key];
}
if (global.process?.env) {
return global.process.env[key];
}
}
20 changes: 19 additions & 1 deletion test/getEnvConfig.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import { EnvConfig, getEnvConfig } from '~/getEnvConfig';

describe('getEnvConfig', () => {
const env = process.env;

beforeEach(() => {
jest.resetModules();
delete (window as unknown as { env?: EnvConfig }).env;
process.env = { ...env };
});

afterEach(() => {
process.env = env;
});

it('should get a config value from window.env', () => {
// given
const config: EnvConfig = {
BACKEND_URL: 'http://localhost:4000',
BACKEND_URL: 'http://localhost:4000/window',
};
(window as unknown as { env?: EnvConfig }).env = config;

Expand All @@ -20,6 +27,17 @@ describe('getEnvConfig', () => {
expect(configBackendUrl).toStrictEqual(config.BACKEND_URL);
});

it('should get a config value from process.env', () => {
// given
process.env.BACKEND_URL = 'http://localhost:4000/process';

// when
const configBackendUrl = getEnvConfig('BACKEND_URL');

// then
expect(configBackendUrl).toStrictEqual(process.env.BACKEND_URL);
});

it('should return undefined when a config value is not set', () => {
// when
const configBackendUrl = getEnvConfig('BACKEND_URL');
Expand Down

0 comments on commit 6efa912

Please sign in to comment.