|
| 1 | +/* global process */ |
| 2 | +import log from 'fancy-log'; |
| 3 | +import dotenv from 'dotenv'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Check if required environment variables are set |
| 7 | + * @param {string[]} requiredVars - Array of required environment variable names |
| 8 | + * @throws {Error} - If any required variables are missing |
| 9 | + */ |
| 10 | +export function checkRequiredEnvVars(requiredVars) { |
| 11 | + const missingVars = requiredVars.filter((varName) => !process.env[varName]); |
| 12 | + |
| 13 | + if (missingVars.length > 0) { |
| 14 | + log.error('ERROR: Missing required environment variables:'); |
| 15 | + missingVars.forEach((v) => log.error(` - ${v}`)); |
| 16 | + console.log(); // eslint-disable-line no-console |
| 17 | + log.info('Make sure to:'); |
| 18 | + log.info('1. Copy .env.example to .env'); |
| 19 | + log.info('2. Fill in all required values in .env'); |
| 20 | + console.log(); // eslint-disable-line no-console |
| 21 | + process.exit(1); |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Loads environment variables from `.env` files based on the current |
| 27 | + * `NODE_ENV`. |
| 28 | + * |
| 29 | + * The function determines the appropriate `.env` files to load in the following |
| 30 | + * order: |
| 31 | + * 1. `.env` - Always included. |
| 32 | + * 2. `.env.local` - Included unless the `NODE_ENV` is `test`. |
| 33 | + * 3. `.env.<NODE_ENV>` - Included based on the current `NODE_ENV`. |
| 34 | + * 4. `.env.<NODE_ENV>.local` - Included based on the current `NODE_ENV`. |
| 35 | + * |
| 36 | + * Files are loaded in the order specified above, and later files override |
| 37 | + * variables from earlier ones. The `.env.local` file is skipped for the `test` |
| 38 | + * environment to ensure consistent test results across different environments. |
| 39 | + */ |
| 40 | +export function loadEnvironmentVariables() { |
| 41 | + const dotenvFiles = [ |
| 42 | + '.env', |
| 43 | + // Don't include `.env.local` for `test` environment |
| 44 | + // since normally you expect tests to produce the same |
| 45 | + // results for everyone |
| 46 | + process.env.NODE_ENV === 'test' ? null : '.env.local', |
| 47 | + `.env.${process.env.NODE_ENV}`, |
| 48 | + `.env.${process.env.NODE_ENV}.local` |
| 49 | + ].filter(Boolean); |
| 50 | + |
| 51 | + dotenvFiles.forEach((dotenvFile) => { |
| 52 | + dotenv.config({ path: dotenvFile }); |
| 53 | + }); |
| 54 | +} |
0 commit comments