feat: configuration CORS dynamique et validation globale dans main.ts
This commit is contained in:
20
src/main.ts
20
src/main.ts
@@ -5,26 +5,36 @@ import { AppModule } from './app.module';
|
|||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create(AppModule);
|
||||||
|
|
||||||
// Configuration CORS
|
// Récupérer les origines CORS depuis la variable d'environnement (séparées par des virgules)
|
||||||
|
const allowedOrigins = process.env.CORS_ORIGIN
|
||||||
|
? process.env.CORS_ORIGIN.split(',').map(origin => origin.trim())
|
||||||
|
: ['http://localhost:3001'];
|
||||||
|
|
||||||
app.enableCors({
|
app.enableCors({
|
||||||
origin: process.env.CORS_ORIGIN || 'http://localhost:3001',
|
origin: (origin, callback) => {
|
||||||
|
// Autoriser si pas d'origine (ex: Postman, curl) ou si origine dans la liste autorisée
|
||||||
|
if (!origin || allowedOrigins.includes(origin)) {
|
||||||
|
callback(null, true);
|
||||||
|
} else {
|
||||||
|
callback(new Error(`Origin ${origin} not allowed by CORS`));
|
||||||
|
}
|
||||||
|
},
|
||||||
credentials: true,
|
credentials: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Configuration de la validation globale
|
|
||||||
app.useGlobalPipes(new ValidationPipe({
|
app.useGlobalPipes(new ValidationPipe({
|
||||||
whitelist: process.env.VALIDATION_WHITELIST === 'true',
|
whitelist: process.env.VALIDATION_WHITELIST === 'true',
|
||||||
forbidNonWhitelisted: process.env.VALIDATION_FORBID_NON_WHITELISTED === 'true',
|
forbidNonWhitelisted: process.env.VALIDATION_FORBID_NON_WHITELISTED === 'true',
|
||||||
transform: process.env.VALIDATION_TRANSFORM === 'true',
|
transform: process.env.VALIDATION_TRANSFORM === 'true',
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Préfixe global pour l'API
|
|
||||||
const apiPrefix = process.env.API_PREFIX || 'api';
|
const apiPrefix = process.env.API_PREFIX || 'api';
|
||||||
app.setGlobalPrefix(apiPrefix);
|
app.setGlobalPrefix(apiPrefix);
|
||||||
|
|
||||||
const port = process.env.PORT || 3000;
|
const port = Number(process.env.PORT) || 3000;
|
||||||
await app.listen(port);
|
await app.listen(port);
|
||||||
console.log(`Application is running on: http://localhost:${port}`);
|
console.log(`Application is running on: http://localhost:${port}`);
|
||||||
console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
|
console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
bootstrap();
|
bootstrap();
|
||||||
|
|||||||
Reference in New Issue
Block a user