Skip to content

Instantly share code, notes, and snippets.

@thekarel
Created April 16, 2019 09:01
Show Gist options
  • Save thekarel/9bca182e01e3b5b4110d77170d28eb55 to your computer and use it in GitHub Desktop.
Save thekarel/9bca182e01e3b5b4110d77170d28eb55 to your computer and use it in GitHub Desktop.
Get config from environment or throw error
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,
}
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