| 1 | /* |
| 2 | * @Author: nevin |
| 3 | * @Date: 2025-01-15 14:17:16 |
| 4 | * @LastEditTime: 2025-02-25 22:17:43 |
| 5 | * @LastEditors: nevin |
| 6 | * @Description: |
| 7 | */ |
| 8 | import { NestFactory } from '@nestjs/core'; |
| 9 | import { AppModule } from './app.module'; |
| 10 | import { NestExpressApplication } from '@nestjs/platform-express'; |
| 11 | import { ConfigService } from '@nestjs/config'; |
| 12 | import { createSwagger } from './_swagger'; |
| 13 | import { |
| 14 | BadRequestException, |
| 15 | HttpStatus, |
| 16 | ValidationPipe, |
| 17 | } from '@nestjs/common'; |
| 18 | import { join } from 'path'; |
| 19 | |
| 20 | async function bootstrap() { |
| 21 | const app = await NestFactory.create<NestExpressApplication>(AppModule, { |
| 22 | bufferLogs: true, |
| 23 | }); |
| 24 | const config = app.get(ConfigService); |
| 25 | |
| 26 | app.enableCors({ |
| 27 | origin: '*', |
| 28 | methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS', |
| 29 | preflightContinue: false, |
| 30 | optionsSuccessStatus: 200, |
| 31 | }); |
| 32 | |
| 33 | app.setGlobalPrefix('api', { exclude: ['/'] }); // 路由添加api开头 |
| 34 | |
| 35 | const { ENABLE_SWAGGER, NODE_ENV, PORT } = config.get('SERVER_CONFIG'); |
| 36 | |
| 37 | const docsUrl = ENABLE_SWAGGER ? createSwagger(app) : ''; // 文档插件 |
| 38 | |
| 39 | app.useGlobalPipes( |
| 40 | new ValidationPipe({ |
| 41 | transform: true, |
| 42 | whitelist: true, |
| 43 | transformOptions: { enableImplicitConversion: true }, |
| 44 | // forbidNonWhitelisted: true, // 禁止 无装饰器验证的数据通过 |
| 45 | errorHttpStatusCode: HttpStatus.BAD_REQUEST, |
| 46 | stopAtFirstError: true, |
| 47 | exceptionFactory: (errors) => |
| 48 | new BadRequestException( |
| 49 | errors.map((e) => { |
| 50 | const rule = Object.keys(e.constraints!)[0]; |
| 51 | const msg = e.constraints![rule]; |
| 52 | return msg; |
| 53 | })[0], |
| 54 | ), |
| 55 | }), |
| 56 | ); |
| 57 | app.useBodyParser('json', { limit: '50mb' }); |
| 58 | app.useBodyParser('urlencoded', { limit: '50mb', extended: true }); |
| 59 | app.setBaseViewsDir(join(__dirname, '..', 'views')); |
| 60 | app.setViewEngine('hbs'); |
| 61 | // app.useGlobalInterceptors( |
| 62 | // new TransformInterceptor(), |
| 63 | // new LoggingInterceptor(), |
| 64 | // ); // 全局注册拦截器 |
| 65 | // app.useGlobalFilters(new HttpExceptionFilter()); // 全局错误拦截器 |
| 66 | await app.listen(PORT); |
| 67 | console.info( |
| 68 | `Application-${NODE_ENV} is running on: http://127.0.0.1:${PORT}`, |
| 69 | ); |
| 70 | console.info(`Swagger Docs: http://127.0.0.1:${PORT}${docsUrl}`); |
| 71 | } |
| 72 | bootstrap(); |
| 73 |