finance-api/src/main.ts
Заид Омар Медхат 33602d0fe9 chore: initialize NestJS project with Docker and environment configuration
Add project scaffolding and development infrastructure:
- Add environment configuration files (.env.development, .env.example) with database, JWT, security, AI integration, logging, and CORS settings
- Add .gitignore to exclude build artifacts, logs, IDE files, and environment variables
- Add .prettierrc with single quotes and trailing commas configuration
- Add multi-stage Dockerfile with development, build, and production stages
- Ad
2025-12-13 15:45:08 +05:00

103 lines
3.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { NestFactory } from '@nestjs/core';
import { ValidationPipe, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import * as cookieParser from 'cookie-parser';
import helmet from 'helmet';
import { AppModule } from './app.module';
async function bootstrap() {
const logger = new Logger('Bootstrap');
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const port = configService.get<number>('app.port') || 3000;
const frontendUrl = configService.get<string>('app.frontendUrl') || 'http://localhost:5173';
const corsOrigins = configService.get<string[]>('app.corsOrigins') || [frontendUrl];
// Security
app.use(helmet());
app.use(cookieParser());
// CORS
app.enableCors({
origin: corsOrigins,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
});
// Global Validation Pipe
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: {
enableImplicitConversion: true,
},
}),
);
// API Prefix
app.setGlobalPrefix('api/v1');
// Swagger Documentation
const swaggerConfig = new DocumentBuilder()
.setTitle('Finance App API')
.setDescription(`
## API для управления личными финансами
### Основные возможности:
- **Аутентификация**: Регистрация, вход, JWT токены в HTTP-only cookies
- **Транзакции**: CRUD операции, фильтрация, аналитика
- **Категории**: Стандартные и пользовательские категории
- **Бюджеты**: Правило 50/30/20, отслеживание расходов
- **AI рекомендации**: Персонализированные советы (Phase 2)
### Безопасность:
- JWT токены в HTTP-only cookies
- Rate limiting
- Защита от XSS и CSRF
### Локализация:
- Все сообщения об ошибках на русском языке
- Поддержка рублей (RUB)
- Московский часовой пояс (UTC+3)
`)
.setVersion('1.0')
.addTag('Аутентификация', 'Регистрация, вход, управление сессиями')
.addTag('Транзакции', 'Управление доходами и расходами')
.addTag('Категории', 'Категории транзакций')
.addTag('Бюджеты (50/30/20)', 'Планирование бюджета по правилу 50/30/20')
.addBearerAuth()
.addCookieAuth('access_token')
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('api/docs', app, document, {
swaggerOptions: {
persistAuthorization: true,
tagsSorter: 'alpha',
operationsSorter: 'alpha',
},
customSiteTitle: 'Finance App API - Документация',
});
// Health check endpoint
app.getHttpAdapter().get('/health', (req, res) => {
res.status(200).json({
status: 'ok',
timestamp: new Date().toISOString(),
});
});
await app.listen(port);
logger.log(`🚀 Application is running on: http://localhost:${port}`);
logger.log(`📚 Swagger documentation: http://localhost:${port}/api/docs`);
logger.log(`🏥 Health check: http://localhost:${port}/health`);
}
bootstrap();