refactor
This commit is contained in:
88
src/js/env-loader.js
Normal file
88
src/js/env-loader.js
Normal file
@@ -0,0 +1,88 @@
|
||||
// env-loader.js
|
||||
// This module is responsible for loading environment variables from .env file
|
||||
|
||||
// Store environment variables in a global object
|
||||
window.ENV_CONFIG = {};
|
||||
|
||||
// Function to load environment variables from .env file
|
||||
async function loadEnvVariables() {
|
||||
try {
|
||||
// Fetch the .env file as text
|
||||
const response = await fetch('/.env');
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn('Could not load .env file. Using default values.');
|
||||
setDefaultEnvValues();
|
||||
return;
|
||||
}
|
||||
|
||||
const envText = await response.text();
|
||||
|
||||
// Parse the .env file content
|
||||
const envVars = parseEnvFile(envText);
|
||||
|
||||
// Store in the global ENV_CONFIG object
|
||||
window.ENV_CONFIG = { ...window.ENV_CONFIG, ...envVars };
|
||||
|
||||
console.log('Environment variables loaded successfully');
|
||||
} catch (error) {
|
||||
console.error('Error loading environment variables:', error);
|
||||
setDefaultEnvValues();
|
||||
}
|
||||
}
|
||||
|
||||
// Parse .env file content into key-value pairs
|
||||
function parseEnvFile(envText) {
|
||||
const envVars = {};
|
||||
|
||||
// Split by lines and process each line
|
||||
envText.split('\n').forEach(line => {
|
||||
// Skip empty lines and comments
|
||||
if (!line || line.trim().startsWith('#')) return;
|
||||
|
||||
// Extract key-value pairs
|
||||
const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
|
||||
if (match) {
|
||||
const key = match[1];
|
||||
let value = match[2] || '';
|
||||
|
||||
// Remove quotes if present
|
||||
if (value.startsWith('"') && value.endsWith('"')) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
|
||||
envVars[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return envVars;
|
||||
}
|
||||
|
||||
// Set default values for required environment variables
|
||||
function setDefaultEnvValues() {
|
||||
window.ENV_CONFIG = {
|
||||
...window.ENV_CONFIG,
|
||||
PUBLIC_VAPID_KEY: 'your_public_vapid_key_here',
|
||||
BACKEND_URL: 'https://your-push-server.example.com'
|
||||
};
|
||||
console.log('Using default environment values');
|
||||
}
|
||||
|
||||
// Export function to initialize environment variables
|
||||
export async function initEnv() {
|
||||
await loadEnvVariables();
|
||||
return window.ENV_CONFIG;
|
||||
}
|
||||
|
||||
// Auto-initialize when imported
|
||||
initEnv();
|
||||
|
||||
// Export access functions for environment variables
|
||||
export function getEnv(key, defaultValue = '') {
|
||||
return window.ENV_CONFIG[key] || defaultValue;
|
||||
}
|
||||
|
||||
export default {
|
||||
initEnv,
|
||||
getEnv
|
||||
};
|
||||
Reference in New Issue
Block a user