Skip to content

Commit

Permalink
feat: handle "on"/"off" as valid boolean type
Browse files Browse the repository at this point in the history
  • Loading branch information
Aleksey Kuznetsov committed Jul 30, 2024
1 parent 598c5ad commit e12b5de
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ URL, email address). To these ends, the following validation functions are avail
- `str()` - Passes string values through, will ensure a value is present unless a
`default` value is given. Note that an empty string is considered a valid value -
if this is undesirable you can easily create your own validator (see below)
- `bool()` - Parses env var strings `"1", "0", "true", "false", "t", "f", "yes", "no"` into booleans
- `bool()` - Parses env var strings `"1", "0", "true", "false", "t", "f", "yes", "no", "on", "off"` into booleans
- `num()` - Parses an env var (eg. `"42", "0.23", "1e5"`) into a Number
- `email()` - Ensures an env var is an email address
- `host()` - Ensures an env var is either a domain name or an ip address (v4 or v6)
Expand Down
2 changes: 2 additions & 0 deletions src/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ export const bool = makeExactValidator<boolean>((input: string | boolean) => {
case 'true':
case 't':
case 'yes':
case 'on':
case '1':
return true
case false:
case 'false':
case 'f':
case 'no':
case 'off':
case '0':
return false
default:
Expand Down
5 changes: 5 additions & 0 deletions tests/validators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ test('bool() works with various formats', () => {
const no = cleanEnv({ FOO: 'no' }, { FOO: bool() })
expect(no).toEqual({ FOO: false })

const on = cleanEnv({ FOO: 'on'}, { FOO: bool() })
expect(on).toEqual({ FOO: true })
const off = cleanEnv({ FOO: 'off' }, { FOO: bool() })
expect(off).toEqual({ FOO: false })

const defaultF = cleanEnv({}, { FOO: bool({ default: false }) })
expect(defaultF).toEqual({ FOO: false })
})
Expand Down

0 comments on commit e12b5de

Please sign in to comment.