Files
superport_v2/lib/core/config/environment.dart
2025-09-29 01:51:47 +09:00

105 lines
2.9 KiB
Dart

import 'package:flutter/foundation.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
/// 환경 설정 로더
///
/// - .env.development / .env.production 파일을 로드하여 런타임 설정을 주입한다.
/// - `--dart-define=ENV=production` 형태로 빌드/실행 시 환경을 지정한다.
/// - 주요 키: `API_BASE_URL`, `FEATURE_*` 플래그들.
class Environment {
Environment._();
/// 현재 환경명 (development | production)
static late final String envName;
/// API 서버 베이스 URL
static late final String baseUrl;
/// 프로덕션 여부
static late final bool isProduction;
static final Map<String, Set<String>> _permissions = {};
/// 환경 초기화
///
/// - 기본 환경은 development이며, `ENV` dart-define 으로 변경 가능
/// - 해당 환경의 .env 파일을 로드하고 핵심 값을 추출한다.
static Future<void> initialize() async {
const envFromDefine = String.fromEnvironment(
'ENV',
defaultValue: 'development',
);
envName = envFromDefine.toLowerCase();
isProduction = envName == 'production';
final fileName = '.env.$envName';
var initialized = false;
try {
await dotenv.load(fileName: fileName);
initialized = true;
} catch (e) {
if (kDebugMode) {
// 개발 편의를 위해 파일 미존재 시 경고만 출력하고 진행
// 실제 배포에서는 파일 존재가 필수다.
// ignore: avoid_print
print('[Environment] $fileName 로드 실패: $e');
}
}
if (!initialized) {
dotenv.testLoad();
}
baseUrl = dotenv.maybeGet('API_BASE_URL') ?? 'http://localhost:8080';
_loadPermissions();
}
/// 기능 플래그 조회 (기본 false)
static bool flag(String key, {bool defaultValue = false}) {
final v = dotenv.maybeGet(key);
if (v == null) return defaultValue;
switch (v.trim().toLowerCase()) {
case '1':
case 'y':
case 'yes':
case 'true':
return true;
case '0':
case 'n':
case 'no':
case 'false':
return false;
default:
return defaultValue;
}
}
static void _loadPermissions() {
_permissions.clear();
for (final entry in dotenv.env.entries) {
const prefix = 'PERMISSION__';
if (!entry.key.startsWith(prefix)) {
continue;
}
final resource = entry.key.substring(prefix.length).toLowerCase();
final values = entry.value
.split(',')
.map((token) => token.trim().toLowerCase())
.where((token) => token.isNotEmpty)
.toSet();
_permissions[resource] = values;
}
}
static bool hasPermission(String resource, String action) {
final actions = _permissions[resource.toLowerCase()];
if (actions == null || actions.isEmpty) {
return true;
}
if (actions.contains('all')) {
return true;
}
return actions.contains(action.toLowerCase());
}
}