Created
April 16, 2019 09:01
-
-
Save thekarel/9bca182e01e3b5b4110d77170d28eb55 to your computer and use it in GitHub Desktop.
Get config from environment or throw error
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
const getEnvConfigOrThrow = (requiredKeys, env) => { | |
const config = requiredKeys.reduce( | |
(result, key) => ({ | |
...result, | |
[key]: env[key], | |
}), | |
{}, | |
) | |
const missingConfig = Object.entries(config).reduce( | |
(missing, [key, value]) => (value ? missing : [...missing, key]), | |
[], | |
) | |
if (missingConfig.length) { | |
throw new Error( | |
`Missing configuration in environment: ${missingConfig.join(', ')}`, | |
) | |
} | |
return config | |
} | |
module.exports = { | |
getEnvConfigOrThrow, | |
} |
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
const {getEnvConfigOrThrow} = require('./getEnvConfigOrThrow') | |
describe('Get Env Config or Throw', () => { | |
it('returns configuration', async () => { | |
expect(getEnvConfigOrThrow(['AAA'], {AAA: 1})).toEqual({AAA: 1}) | |
}) | |
it('returns only relevant configuration', async () => { | |
expect(getEnvConfigOrThrow(['BBB'], {AAA: 1, BBB: 2})).toEqual({BBB: 2}) | |
}) | |
it('throws error for missing config', async () => { | |
const call = () => getEnvConfigOrThrow(['BBB'], {}) | |
expect(call).toThrowErrorMatchingInlineSnapshot( | |
`"Missing configuration in environment: BBB"`, | |
) | |
}) | |
it('throws error for multilpe missing config', async () => { | |
const call = () => getEnvConfigOrThrow(['BBB', 'CCC'], {}) | |
expect(call).toThrowErrorMatchingInlineSnapshot( | |
`"Missing configuration in environment: BBB, CCC"`, | |
) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment