import { RequestMethod, ValidationPipe } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; import { NestExpressApplication } from '@nestjs/platform-express'; import express, { type NextFunction, type Request, type Response } from 'express'; import { AppModule } from './AppModule'; import { altchaMiddleware } from './middlewares/altchaMiddleware'; import { AltchaService } from './modules/altcha/services/AltchaService'; import { Config } from './types/config/Config'; import { HttpMethod } from './types/HttpMethod'; import { NodeEnv } from './types/NodeEnv'; async function bootstrap() { const app = await NestFactory.create(AppModule, { bodyParser: false }); app.setGlobalPrefix('api', { exclude: [ { path: 'i/:id/:secret', method: RequestMethod.GET }, { path: 'i/:accessToken', method: RequestMethod.GET } ] }); const configService = app.get(ConfigService); const altchaService = app.get(AltchaService); const { port, nodeEnv, corsOrigins, validation: { upload: { maxRequestBodyBytes } } } = configService.get('app') as Config['app']; const defaultJsonParser = express.json(); const uploadJsonParser = express.json({ limit: maxRequestBodyBytes }); const uploadAltchaMiddleware = altchaMiddleware(altchaService); app.use((req: Request, res: Response, next: NextFunction) => { if (req.method === HttpMethod.Post && req.path.startsWith('/api/uploads')) { return uploadAltchaMiddleware(req, res, (err: unknown) => { if (err) { return next(err); } return uploadJsonParser(req, res, next); }); } return defaultJsonParser(req, res, next); }); app.useGlobalPipes( new ValidationPipe({ transform: true, transformOptions: { enableImplicitConversion: true } }) ); if (nodeEnv === NodeEnv.Development) { app.enableCors({ origin: corsOrigins, credentials: true }); } app.set('trust proxy', 1); await app.listen(port); } void bootstrap();