Skip to content

Instantly share code, notes, and snippets.

@joseluisq
Last active July 26, 2018 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joseluisq/c156d6fb268a1685e810ea2b474035d6 to your computer and use it in GitHub Desktop.
Save joseluisq/c156d6fb268a1685e810ea2b474035d6 to your computer and use it in GitHub Desktop.
Environment variables validator
const env = (key) => process.env[key] || null
const debug = (obj) => console.dir(obj, { colors: true })
const validator = (vlist = []) => {
const errors = []
vlist.forEach(v => {
if (!env(v)) errors.push(`No '${v}' supplied!`, v)
})
return {
valid: () => !!!errors.length,
errors: () => {
console.log('ERRORS:')
errors.forEach(error => console.log(` - ${error}`))
process.exit(1)
}
}
}
module.exports = {
env,
debug,
validator
}
@joseluisq
Copy link
Author

joseluisq commented Jul 26, 2018

Usage:

const { validator } = require('./env_validator');

// My validation list
const vlist = [
  'DB_HOST',
  'DB_NAME',
  'DB_USER',
  'DB_PASSWD'
]

const v = validator(vlist)

if (v.valid())
  // ok, continue...
else
  // display errors!
  v.errors()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment