Skip to content

Commit

Permalink
Merge pull request #21 from SimenB/bool-false
Browse files Browse the repository at this point in the history
Allow passing in `false` to `bool`
  • Loading branch information
af committed Dec 28, 2016
2 parents 3d711b3 + 635a0ff commit 68f95bd
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
8 changes: 6 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,19 @@ function cleanEnv(inputEnv, specs = {}, options = {}) {
for (const k of varKeys) {
const spec = specs[k]
const devDefault = (env.NODE_ENV === 'production' ? undefined : spec.devDefault)
const rawValue = env[k] || (devDefault === undefined ? spec.default : devDefault)
let rawValue = env[k]

if (rawValue === undefined) {
rawValue = (devDefault === undefined ? spec.default : devDefault)
}

// Default values can be anything falsy (besides undefined), without
// triggering validation errors:
const usingFalsyDefault = ((spec.default !== undefined) && (spec.default === rawValue)) ||
((devDefault !== undefined) && (devDefault === rawValue))

try {
if (!rawValue && !usingFalsyDefault) throw new EnvMissingError(spec.desc || '')
if (rawValue === undefined && !usingFalsyDefault) throw new EnvMissingError(spec.desc || '')
output[k] = validateVar({ name: k, spec, rawValue })
} catch (err) {
if (options.reporter === null) throw err
Expand Down
7 changes: 6 additions & 1 deletion tests/test_types.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,16 @@ const test = createGroup()
const makeSilent = { reporter: null }


test('bool() works with various boolean string formats', () => {
test('bool() works with various formats', () => {
assert.equal(bool().type, 'bool')
assert.throws(() => cleanEnv({ FOO: 'asfd' }, { FOO: bool() }, makeSilent),
EnvError, 'Invalid value')

const trueBool = cleanEnv({ FOO: true }, { FOO: bool() })
assert.deepEqual(trueBool, { FOO: true })
const falseBool = cleanEnv({ FOO: false }, { FOO: bool() })
assert.deepEqual(falseBool, { FOO: false })

const truthyNum = cleanEnv({ FOO: '1' }, { FOO: bool() })
assert.deepEqual(truthyNum, { FOO: true })
const falsyNum = cleanEnv({ FOO: '0' }, { FOO: bool() })
Expand Down

0 comments on commit 68f95bd

Please sign in to comment.