Files
canina/backend/src/main.ts
T
parsa aghaei 812bc2920c
Deploy Canina / deploy (push) Successful in 1m46s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 6s
feat(navigation): add custom glowing NavigationProgressBar, enable Swagger on localhost dev, set local store port to 3005, and remove hero-section-image.png
2026-08-29 13:53:21 +03:30

130 lines
4.0 KiB
TypeScript

import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import { join } from 'path';
import { ValidationPipe, BadRequestException } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { CustomHttpExceptionFilter } from './common/filters/http-exception.filter';
import { PrismaExceptionFilter } from './common/filters/prisma-exception.filter';
import { DecimalInterceptor } from './common/interceptors/decimal.interceptor';
import { validateEnv } from './common/env.validation';
import helmet from 'helmet';
import compression from 'compression';
// Ensure BigInt can be serialized to JSON across all NestJS / Express responses
(BigInt.prototype as any).toJSON = function () {
return Number(this);
};
async function bootstrap() {
validateEnv(process.env);
process.env.JWT_ACCESS_SECRET =
process.env.JWT_ACCESS_SECRET ||
process.env.JWT_SECRET ||
'canina_jwt_fallback_access_secret_32_characters_minimum_len_2026';
process.env.JWT_REFRESH_SECRET =
process.env.JWT_REFRESH_SECRET ||
'canina_jwt_fallback_refresh_secret_32_characters_minimum_len_2026';
const app = await NestFactory.create<NestExpressApplication>(AppModule);
// Trust reverse proxy (Nginx / Docker ingress) to resolve real client IP from X-Forwarded-For
app.set('trust proxy', true);
// Serve static uploads folder with 1-year aggressive browser caching (immutable)
const staticUploadOptions = {
maxAge: 31536000000, // 1 year in ms
immutable: true,
setHeaders: (res: any) => {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
},
};
app.useStaticAssets(join(process.cwd(), 'uploads'), {
prefix: '/uploads/',
...staticUploadOptions,
});
app.useStaticAssets(join(process.cwd(), 'uploads'), {
prefix: '/api/uploads/',
...staticUploadOptions,
});
app.use(compression());
app.use(
helmet({
contentSecurityPolicy: false, // Avoid blocking Swagger UI scripts and assets
}),
);
app.setGlobalPrefix('api');
app.enableCors({
origin: true,
credentials: true,
});
app.useGlobalPipes(
new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
exceptionFactory: (errors) => {
const formattedDetails = errors.map((err) => {
const constraints = err.constraints
? Object.values(err.constraints)
: [];
return {
field: err.property,
message:
constraints.length > 0
? constraints[0]
: 'مقدار وارد شده نامعتبر است.',
};
});
return new BadRequestException({
message:
'اطلاعات ورودی فرم معتبر نمی‌باشد. لطفاً موارد مشخص شده را اصلاح نمایید.',
error: 'INVALID_INPUT_DATA',
details: formattedDetails,
});
},
}),
);
app.useGlobalFilters(
new CustomHttpExceptionFilter(),
new PrismaExceptionFilter(),
);
app.useGlobalInterceptors(new DecimalInterceptor());
const isProduction = process.env.NODE_ENV === 'production';
const isSwaggerExplicitlyDisabled = process.env.ENABLE_SWAGGER === 'false';
if (!isProduction && !isSwaggerExplicitlyDisabled) {
const config = new DocumentBuilder()
.setTitle('Canina Iran API')
.setDescription(
'API Documentation for Canina Iran Pet Health & Supplement Platform',
)
.setVersion('1.0.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/docs', app, document);
console.log('Swagger UI is ACTIVE on /api/docs');
} else {
console.log('Swagger UI is DISABLED for security (production environment)');
}
await app.listen(process.env.PORT ?? 4001);
}
bootstrap().catch((err: unknown) => {
console.error('Bootstrap error:', err);
process.exit(1);
});