83 lines
2.7 KiB
TypeScript
83 lines
2.7 KiB
TypeScript
import { NestFactory } from '@nestjs/core';
|
|
import { ValidationPipe } from '@nestjs/common';
|
|
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import helmet from 'helmet';
|
|
import { AppModule } from './app/app.module';
|
|
import { writeFileSync } from 'fs';
|
|
import { join } from 'path';
|
|
|
|
async function bootstrap() {
|
|
const app = await NestFactory.create(AppModule);
|
|
const configService = app.get(ConfigService);
|
|
|
|
// ✅ Security Middlewares
|
|
app.use(helmet());
|
|
app.enableCors({
|
|
origin: [
|
|
'http://localhost:3000', // Local Swagger UI
|
|
'http://localhost:5173', // Local Frontend
|
|
'https://editor.swagger.io', // Swagger Editor
|
|
'https://klc-admin.wdiprojects.com',
|
|
'https://admin-uat.klc.betadelivery.com',
|
|
],
|
|
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
|
|
credentials: true,
|
|
});
|
|
|
|
// ✅ Global prefix
|
|
const globalPrefix = configService.get('API_PREFIX') || 'api/v1';
|
|
app.setGlobalPrefix(globalPrefix);
|
|
|
|
// ✅ Logging middleware
|
|
app.use((req, _res, next) => {
|
|
console.log(`📝 ${new Date().toISOString()} - ${req.method} ${req.url}`);
|
|
next();
|
|
});
|
|
|
|
// ✅ Global validation
|
|
app.useGlobalPipes(
|
|
new ValidationPipe({
|
|
whitelist: true,
|
|
forbidNonWhitelisted: true,
|
|
transform: true,
|
|
transformOptions: {
|
|
enableImplicitConversion: true,
|
|
},
|
|
}),
|
|
);
|
|
|
|
// ✅ Swagger setup (only for local/dev)
|
|
if (configService.get('NODE_ENV') !== 'production') {
|
|
const swaggerConfig = new DocumentBuilder()
|
|
.setTitle('Minglar API')
|
|
.setDescription('NestJS Backend for Minglar with Lambda-ready endpoints')
|
|
.setVersion(configService.get('API_VERSION') || '1.0.0')
|
|
.addBearerAuth()
|
|
.addServer(`${process.env.SERVER_URL || 'http://localhost:3000'}/`, 'Local Server')
|
|
.build();
|
|
|
|
const document = SwaggerModule.createDocument(app, swaggerConfig);
|
|
SwaggerModule.setup('api/docs', app, document);
|
|
|
|
// Optionally write swagger.json for offline usage
|
|
const outputPath = join(process.cwd(), 'swagger.json');
|
|
writeFileSync(outputPath, JSON.stringify(document, null, 2), 'utf8');
|
|
console.log(`✅ Swagger JSON file generated at: ${outputPath}`);
|
|
}
|
|
|
|
// ✅ Start app (only for local or non-Lambda)
|
|
const port = configService.get('PORT') || 3000;
|
|
await app.listen(port);
|
|
|
|
console.log(`🚀 Server running at http://localhost:${port}`);
|
|
if (configService.get('NODE_ENV') !== 'production') {
|
|
console.log(`📚 Swagger docs: http://localhost:${port}/api/docs`);
|
|
}
|
|
}
|
|
|
|
// Only run bootstrap if not in AWS Lambda
|
|
if (!process.env.AWS_LAMBDA_FUNCTION_NAME) {
|
|
bootstrap();
|
|
}
|