Instantly share code, notes, and snippets.

Embed
What would you like to do?
constructor(filePath: string) {
let config;
if (fs.existsSync(filePath)) { // Look for the specified file first
config = dotenv.parse(fs.readFileSync(filePath));
} else { // Fallback to checking if they are defined in the process.env already
config = [
'TYPEORM_USERNAME',
'TYPEORM_PASSWORD',
// etc...
].reduce((acc, val) => (acc[val] = process.env[val], acc), {});
}
this.envConfig = this.validateInput(config);
}
// Check if the incoming object conforms to rules. Omission of
// required() variables will not let the app function correctly
// and will throw an error
private validateInput(envConfig: EnvConfig): EnvConfig {
const envVarsSchema: Joi.ObjectSchema = Joi.object({
TYPEORM_USERNAME: Joi.string().required(),
TYPEORM_PASSWORD: Joi.string().required(),
// etc...
});
const { error, value: validatedEnvConfig } = Joi.validate(
envConfig,
envVarsSchema,
);
if (error) {
throw new Error(`Config validation error: ${error.message}`);
}
return validatedEnvConfig;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment