feat: 搭建 NestJS 后端基础设施与 Prisma 数据模型
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
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';
|
||||
|
||||
// 让 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>('h5Origin') 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(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',
|
||||
});
|
||||
|
||||
// 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();
|
||||
Reference in New Issue
Block a user