Skip to content

Commit c2d52a5

Browse files
committed
fix(api): centralize and correct dotenv loading in EnvironmentConfig
Refactors environment variable handling to be self-contained within the `EnvironmentConfig` class. - `EnvironmentConfig` now creates a static `DotEnv` instance, loads the `.env` file, and all getters now read from this instance instead of `Platform.environment`. - This ensures that environment variables are loaded and read correctly from a single, reliable source, resolving the issue where variables were not available to the application.
1 parent 87786c2 commit c2d52a5

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

lib/src/config/environment_config.dart

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import 'dart:io';
22
import 'package:logging/logging.dart';
3+
import 'package:dotenv/dotenv.dart';
34

45
/// {@template environment_config}
56
/// A utility class for accessing environment variables.
@@ -9,20 +10,25 @@ import 'package:logging/logging.dart';
910
/// connection strings are managed outside of the source code.
1011
/// {@endtemplate}
1112
abstract final class EnvironmentConfig {
12-
/// Retrieves the PostgreSQL database connection URI from the environment.
1313
static final _log = Logger('EnvironmentConfig');
14+
15+
// The DotEnv instance that loads the .env file and platform variables.
16+
// It's initialized once and reused.
17+
static final _env = DotEnv(includePlatformEnvironment: true)..load();
18+
19+
/// Retrieves the PostgreSQL database connection URI from the environment.
1420
///
1521
/// The value is read from the `DATABASE_URL` environment variable.
1622
///
1723
/// Throws a [StateError] if the `DATABASE_URL` environment variable is not
1824
/// set, as the application cannot function without it.
1925
static String get databaseUrl {
20-
final dbUrl = Platform.environment['DATABASE_URL'];
26+
final dbUrl = _env['DATABASE_URL'];
2127
if (dbUrl == null || dbUrl.isEmpty) {
2228
_log.severe(
2329
'DATABASE_URL not found. Dumping available environment variables:',
2430
);
25-
Platform.environment.forEach((key, value) {
31+
_env.map.forEach((key, value) {
2632
_log.severe(' - $key: $value');
2733
});
2834
throw StateError(
@@ -37,5 +43,5 @@ abstract final class EnvironmentConfig {
3743
///
3844
/// The value is read from the `ENV` environment variable.
3945
/// Defaults to 'production' if the variable is not set.
40-
static String get environment => Platform.environment['ENV'] ?? 'production';
46+
static String get environment => _env['ENV'] ?? 'production';
4147
}

0 commit comments

Comments
 (0)