fix: lỗi đọc nhầm .env ở thư mục backend

This commit is contained in:
2026-06-19 08:13:35 +07:00
parent 623f0164c8
commit 6f2dd0fc01
5 changed files with 88 additions and 54 deletions
+17 -28
View File
@@ -1,24 +1,6 @@
import * as dotenv from 'dotenv';
import * as path from 'path';
import * as fs from 'fs';
// Tự động tìm kiếm file .env ở nhiều vị trí để đảm bảo tải đúng trong môi trường monorepo
const possibleEnvPaths = [
path.resolve(process.cwd(), '.env'),
path.resolve(process.cwd(), '..', '.env'),
path.resolve(__dirname, '..', '.env'),
path.resolve(__dirname, '..', '..', '.env'),
];
let loadedEnvPath: string | null = null;
for (const p of possibleEnvPaths) {
if (fs.existsSync(p)) {
dotenv.config({ path: p });
console.log(`[Config] 📂 Biến môi trường được tải từ: ${p}`);
loadedEnvPath = p;
break;
}
}
import { ConfigModule, ConfigService } from '@nestjs/config';
import 'reflect-metadata';
import * as zlib from 'zlib';
@@ -62,14 +44,6 @@ const CACHE_TTL = {
};
async function bootstrap() {
if (!process.env.DATABASE_URL) {
throw new Error('❌ DATABASE_URL không tồn tại trong biến môi trường! Kiểm tra file .env tại: ' + (loadedEnvPath || 'một trong các đường dẫn đã thử: ' + possibleEnvPaths.join(', ')));
}
// Kiểm tra log xem biến môi trường đã nhận đúng chưa
console.log('====================================');
console.log('DATABASE_URL:', process.env.DATABASE_URL);
console.log('====================================');
// Chuyển sang dùng NestExpressApplication để cấu hình static assets
const app = await NestFactory.create<NestExpressApplication>(AppModule);
@@ -279,6 +253,11 @@ class AuthController {
constructor(
private prisma: PrismaService,
private jwtService: JwtService,
// Inject ConfigService để đọc biến môi trường một cách an toàn
// NestJS sẽ đảm bảo ConfigModule được tải trước khi AuthController được khởi tạo
// Do đó, các biến môi trường sẽ luôn có sẵn ở đây.
// Điều này cũng áp dụng cho EmailService.
private configService: ConfigService,
private emailService: EmailService,
@Inject(CACHE_MANAGER) private cacheManager: Cache
) {}
@@ -1716,6 +1695,13 @@ class AdminOtpController {
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true, // Giúp ConfigModule có sẵn ở mọi nơi trong ứng dụng
// Chỉ định đường dẫn tới file .env ở thư mục gốc của dự án
envFilePath: path.resolve(__dirname, '..', '..', '.env'),
// Bỏ qua lỗi nếu không tìm thấy file .env (hữu ích cho môi trường production dùng biến hệ thống)
ignoreEnvFile: process.env.NODE_ENV === 'production',
}),
CacheModule.registerAsync({
isGlobal: true,
useFactory: async () => ({
@@ -1731,13 +1717,16 @@ class AdminOtpController {
}) as any,
],
controllers: [AppController, AuthController, PublicTourController, TourController, UserController, RoutingController, LegController, LocationController, CommentController, PhotoController, AdminOtpController],
providers: [PrismaService, JwtStrategy, TourRoleGuard, JwtAuthGuard, AdminGuard, CommentGateway, Reflector, EmailService],
providers: [PrismaService, JwtStrategy, TourRoleGuard, JwtAuthGuard, AdminGuard, CommentGateway, Reflector, EmailService, ConfigService],
exports: [PrismaService]
})
class AppModule {}
bootstrap().catch(err => {
if (err.message.includes('DATABASE_URL')) {
console.error('❌ Lỗi nghiêm trọng: Biến môi trường DATABASE_URL không được tải. Hãy chắc chắn rằng file .env tồn tại ở thư mục gốc của dự án và chứa giá trị này.');
}
console.error('💥 Lỗi khởi động Server:');
console.error(err);
process.exit(1);