1 | initial version |
The method for creating a loader for environment variables that ensures type safety involves the following steps:
Here is an example code snippet in Node.js using dotenv and joi libraries:
const dotenv = require('dotenv');
const Joi = require('joi');
dotenv.config();
const envVarsSchema = Joi.object({
NODE_ENV: Joi.string()
.valid('development', 'production', 'test', 'provision')
.required(),
PORT: Joi.number()
.default(3000),
API_KEY: Joi.string()
.required()
}).unknown(true);
const { error, value: envVars } = envVarsSchema.validate(process.env);
if (error) {
throw new Error(`Config validation error: ${error.message}`);
}
module.exports = {
env: envVars.NODE_ENV,
port: envVars.PORT,
apiKey: envVars.API_KEY,
};
In this example, we define a schema for our environment variables using Joi, which specifies the expected data types and validates the values. We then load the environment variables using dotenv and validate them using Joi's validate()
method. If there is an error, an exception is thrown. Otherwise, we export the validated environment variables.