Skip to content

Commit

Permalink
Try to suggest typos
Browse files Browse the repository at this point in the history
Ref af#45
  • Loading branch information
SimenB authored and tuannm151 committed Jul 1, 2024
1 parent b678b72 commit f301a77
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
13 changes: 13 additions & 0 deletions lib/strictProxy.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
const meant = require('meant')


const didYouMean = (scmd, commands) => {
const bestSimilarity = meant(scmd, commands)

if (bestSimilarity.length > 0) {
throw new ReferenceError(`[envalid] Environment var ${scmd} not found, did you mean ${bestSimilarity.join(', ')}?`)
}
}

/**
* Wrap the environment object with a Proxy that throws when:
* a) trying to mutate an env var
Expand All @@ -19,6 +30,8 @@ module.exports = (envObj, originalEnv) => new Proxy(envObj, {
throw new ReferenceError(`[envalid] Environment accessed not found in envalid, but in the environment. Please add a validator for it: ${name}`)
}

didYouMean(name, Object.keys(envObj))

throw new ReferenceError(`[envalid] Environment var not found: ${name}`)
}

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
"license": "MIT",
"dependencies": {
"chalk": "2.1.0",
"dotenv": "4.0.0"
"dotenv": "4.0.0",
"meant": "1.0.0"
},
"typings": "envalid.d.ts"
}
7 changes: 7 additions & 0 deletions tests/test_strict.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,10 @@ test('strict mode objects throw and suggest add validator if in orig env', () =>
}, strictOption)
assert.throws(() => env.FOO, '[envalid] Environment accessed not found in envalid, but in the environment. Please add a validator for it: FOO')
})

test('strict mode objects throw and suggest typo', () => {
const env = cleanEnv({}, {
BAR: str()
}, strictOption)
assert.throws(() => env.BAS, '[envalid] Environment var BAS not found, did you mean BAR?')
})

0 comments on commit f301a77

Please sign in to comment.