Files
Artveris/apps/api/src/main.ts
T

84 lines
2.8 KiB
TypeScript

import 'reflect-metadata';
import { NestFactory } from '@nestjs/core';
import { ValidationPipe, RequestMethod, Logger } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ConfigService } from '@nestjs/config';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { existsSync, mkdirSync } from 'fs';
import { resolve } from 'path';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { OperationLogInterceptor } from './operation-log/operation-log.interceptor';
import { STATIC_ASSET_CACHE_CONTROL } from './storage/storage.service';
// 让 BigInt 可被 JSON 序列化为字符串,避免精度问题。
(BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () {
return this.toString();
};
async function bootstrap(): Promise<void> {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
bodyParser: true,
});
const config = app.get(ConfigService);
const logger = new Logger('Bootstrap');
app.setGlobalPrefix('api', {
exclude: [{ path: 't/:shortCode', method: RequestMethod.GET }],
});
app.enableCors({
origin: [
config.get<string>('adminOrigin') as string,
config.get<string>('clientOrigin') as string,
/^http:\/\/localhost(:\d+)?$/,
/^http:\/\/127\.0\.0\.1(:\d+)?$/,
],
credentials: true,
});
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
transformOptions: { enableImplicitConversion: true },
}),
);
app.useGlobalFilters(new AllExceptionsFilter());
app.useGlobalInterceptors(app.get(OperationLogInterceptor), new TransformInterceptor());
// 本地文件存储静态访问
const localDir = resolve(config.get<string>('storage.localDir') || './storage');
if (!existsSync(localDir)) {
mkdirSync(localDir, { recursive: true });
}
app.useStaticAssets(localDir, {
prefix: config.get<string>('storage.publicPrefix') || '/uploads',
etag: true,
lastModified: true,
maxAge: '1y',
immutable: true,
setHeaders: (res) => {
res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL);
},
});
// Swagger(开发文档)
const swaggerConfig = new DocumentBuilder()
.setTitle('artveris API')
.setDescription('艺术品可信溯源与认证系统接口文档')
.setVersion('0.1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('api/docs', app, document);
const port = config.get<number>('port') || 3000;
await app.listen(port);
logger.log(`API 已启动: http://localhost:${port}/api`);
logger.log(`接口文档: http://localhost:${port}/api/docs`);
}
void bootstrap();