Created
September 23, 2022 04:14
-
-
Save 0xYao/867bc6ef65cfa836cc433df95b7a7797 to your computer and use it in GitHub Desktop.
Environment variables validation script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fs from 'fs'; | |
import dotenv from 'dotenv'; | |
type ValidationErorr = { | |
property: string; | |
message: string; | |
}; | |
class ValidationError extends Error {} | |
const optionalKeys = ['PORT']; | |
const main = () => { | |
if (process.argv.length !== 3) { | |
throw new Error('Arguments length must be 3.'); | |
} | |
const envFilename = process.argv[2]; | |
const envFileString = fs.readFileSync(envFilename, { encoding: 'utf-8' }); | |
const envData = dotenv.parse(envFileString); | |
const sampleEnvFileString = fs.readFileSync('.env.sample', { encoding: 'utf-8' }); | |
const sampleEnvData = dotenv.parse(sampleEnvFileString); | |
const errors: ValidationErorr[] = []; | |
Object.keys(sampleEnvData).forEach((envKey) => { | |
const envValue = envData[envKey]; | |
if (!(envKey in envData) && !optionalKeys.includes(envKey)) { | |
errors.push({ property: envKey, message: `${envKey} is missing.` }); | |
} else if (envValue?.trim() === '') { | |
errors.push({ property: envKey, message: `${envKey} must have a value.` }); | |
} | |
}); | |
if (errors.length > 0) { | |
throw new ValidationError(JSON.stringify(errors, null, 2)); | |
} | |
console.log('Successfully validated the environment variables!'); | |
}; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment