feat: 搭建 NestJS 后端基础设施与 Prisma 数据模型
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { ApiTags, ApiOperation } from '@nestjs/swagger';
|
||||
import { Public } from './common/decorators/public.decorator';
|
||||
|
||||
@ApiTags('系统')
|
||||
@Controller()
|
||||
export class AppController {
|
||||
constructor(private readonly config: ConfigService) {}
|
||||
|
||||
@Public()
|
||||
@Get('health')
|
||||
@ApiOperation({ summary: '健康检查' })
|
||||
health() {
|
||||
return { status: 'ok', time: new Date().toISOString() };
|
||||
}
|
||||
|
||||
@Public()
|
||||
@Get('app-info')
|
||||
@ApiOperation({ summary: '应用基本信息(公开)' })
|
||||
appInfo() {
|
||||
return { appName: this.config.get<string>('appName') };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import configuration from './config/configuration';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
import { AppController } from './app.controller';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
load: [configuration],
|
||||
envFilePath: ['../../.env', '.env'],
|
||||
}),
|
||||
PrismaModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
|
||||
export interface AuthUser {
|
||||
id: number;
|
||||
username: string;
|
||||
role: string;
|
||||
realName?: string;
|
||||
}
|
||||
|
||||
export const CurrentUser = createParamDecorator(
|
||||
(data: keyof AuthUser | undefined, ctx: ExecutionContext): AuthUser | unknown => {
|
||||
const request = ctx.switchToHttp().getRequest();
|
||||
const user = request.user as AuthUser;
|
||||
return data ? user?.[data] : user;
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const IS_PUBLIC_KEY = 'isPublic';
|
||||
// 标记接口为公开(无需登录),用于 C 端溯源等匿名访问。
|
||||
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||
@@ -0,0 +1,6 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import { RoleType } from '@artveris/shared';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
// 限定可访问的角色;未标注则任意已登录用户可访问。
|
||||
export const Roles = (...roles: RoleType[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -0,0 +1,28 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsInt, IsOptional, Max, Min } from 'class-validator';
|
||||
|
||||
export class PaginationDto {
|
||||
@ApiPropertyOptional({ description: '页码,从 1 开始', default: 1 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page = 1;
|
||||
|
||||
@ApiPropertyOptional({ description: '每页条数', default: 10 })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
@Max(200)
|
||||
pageSize = 10;
|
||||
|
||||
get skip(): number {
|
||||
return (this.page - 1) * this.pageSize;
|
||||
}
|
||||
|
||||
get take(): number {
|
||||
return this.pageSize;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { ErrorMessage } from '@artveris/shared';
|
||||
|
||||
// 业务异常:携带统一业务码,由全局过滤器转换为标准响应体。
|
||||
export class BusinessException extends Error {
|
||||
constructor(
|
||||
public readonly code: number,
|
||||
message?: string,
|
||||
public readonly httpStatus = 400,
|
||||
) {
|
||||
super(message || ErrorMessage[code] || '业务处理失败');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { ErrorCode } from '@artveris/shared';
|
||||
import { BusinessException } from '../exceptions/business.exception';
|
||||
|
||||
@Catch()
|
||||
export class AllExceptionsFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger('Exception');
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost): void {
|
||||
const ctx = host.switchToHttp();
|
||||
const res = ctx.getResponse<Response>();
|
||||
|
||||
let httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
let code: number = ErrorCode.INTERNAL_ERROR;
|
||||
let message = '服务器内部错误';
|
||||
|
||||
if (exception instanceof BusinessException) {
|
||||
httpStatus = exception.httpStatus;
|
||||
code = exception.code;
|
||||
message = exception.message;
|
||||
} else if (exception instanceof HttpException) {
|
||||
httpStatus = exception.getStatus();
|
||||
const r = exception.getResponse();
|
||||
if (typeof r === 'string') {
|
||||
message = r;
|
||||
} else if (r && typeof r === 'object') {
|
||||
const m = (r as Record<string, unknown>).message;
|
||||
message = Array.isArray(m) ? String(m[0]) : String(m ?? exception.message);
|
||||
}
|
||||
code = this.mapStatusToCode(httpStatus);
|
||||
} else {
|
||||
this.logger.error(
|
||||
(exception as Error)?.message ?? String(exception),
|
||||
(exception as Error)?.stack,
|
||||
);
|
||||
}
|
||||
|
||||
res.status(httpStatus).json({ code, message, data: null });
|
||||
}
|
||||
|
||||
private mapStatusToCode(status: number): number {
|
||||
switch (status) {
|
||||
case HttpStatus.BAD_REQUEST:
|
||||
return ErrorCode.VALIDATION_FAILED;
|
||||
case HttpStatus.UNAUTHORIZED:
|
||||
return ErrorCode.UNAUTHORIZED;
|
||||
case HttpStatus.FORBIDDEN:
|
||||
return ErrorCode.FORBIDDEN;
|
||||
case HttpStatus.NOT_FOUND:
|
||||
return ErrorCode.NOT_FOUND;
|
||||
case HttpStatus.TOO_MANY_REQUESTS:
|
||||
return ErrorCode.TOO_MANY_REQUESTS;
|
||||
default:
|
||||
return ErrorCode.INTERNAL_ERROR;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ApiResponse } from '@artveris/shared';
|
||||
|
||||
// 将控制器返回值统一包裹为 { code, message, data }。
|
||||
@Injectable()
|
||||
export class TransformInterceptor<T> implements NestInterceptor<T, ApiResponse<T>> {
|
||||
intercept(_context: ExecutionContext, next: CallHandler<T>): Observable<ApiResponse<T>> {
|
||||
return next.handle().pipe(
|
||||
map((data) => {
|
||||
if (
|
||||
data &&
|
||||
typeof data === 'object' &&
|
||||
'code' in (data as object) &&
|
||||
'message' in (data as object) &&
|
||||
'data' in (data as object)
|
||||
) {
|
||||
return data as unknown as ApiResponse<T>;
|
||||
}
|
||||
return { code: 0, message: 'success', data: (data ?? null) as T | null };
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PageResult } from '@artveris/shared';
|
||||
|
||||
export function buildPage<T>(list: T[], total: number, page: number, pageSize: number): PageResult<T> {
|
||||
return { list, total, page, pageSize };
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
export interface AppConfig {
|
||||
appName: string;
|
||||
env: string;
|
||||
port: number;
|
||||
baseUrl: string;
|
||||
publicTracePath: string;
|
||||
adminOrigin: string;
|
||||
h5Origin: string;
|
||||
traceUrlTemplate: string;
|
||||
jwt: { secret: string; expiresIn: string };
|
||||
redis: { host: string; port: number; password?: string };
|
||||
storage: {
|
||||
driver: 'local' | 'oss';
|
||||
localDir: string;
|
||||
publicPrefix: string;
|
||||
cdnBaseUrl: string;
|
||||
oss: {
|
||||
endpoint: string;
|
||||
region: string;
|
||||
bucket: string;
|
||||
accessKeyId: string;
|
||||
accessKeySecret: string;
|
||||
};
|
||||
};
|
||||
blockchain: {
|
||||
driver: 'mock' | 'tianhe';
|
||||
tianhe: { baseUrl: string; appId: string; appKey: string };
|
||||
};
|
||||
geo: { driver: string };
|
||||
seedAdmin: { username: string; password: string; name: string };
|
||||
logRetentionDays: number;
|
||||
watermarkText: string;
|
||||
}
|
||||
|
||||
export default (): AppConfig => {
|
||||
const h5Origin = process.env.H5_ORIGIN || 'http://localhost:5174';
|
||||
return {
|
||||
appName: process.env.APP_NAME || '艺术品可信溯源与认证平台',
|
||||
env: process.env.NODE_ENV || 'development',
|
||||
port: parseInt(process.env.API_PORT || '3000', 10),
|
||||
baseUrl: process.env.BASE_URL || 'http://localhost:3000',
|
||||
publicTracePath: process.env.PUBLIC_TRACE_PATH || '/t',
|
||||
adminOrigin: process.env.ADMIN_ORIGIN || 'http://localhost:5173',
|
||||
h5Origin,
|
||||
// 短链跳转到 C 端溯源页的地址模板,{code} 会被替换为短码
|
||||
traceUrlTemplate:
|
||||
process.env.TRACE_URL_TEMPLATE || `${h5Origin}/#/pages/trace/index?code={code}`,
|
||||
jwt: {
|
||||
secret: process.env.JWT_SECRET || 'artveris_dev_secret',
|
||||
expiresIn: process.env.JWT_EXPIRES_IN || '7d',
|
||||
},
|
||||
redis: {
|
||||
host: process.env.REDIS_HOST || 'localhost',
|
||||
port: parseInt(process.env.REDIS_PORT || '6379', 10),
|
||||
password: process.env.REDIS_PASSWORD || undefined,
|
||||
},
|
||||
storage: {
|
||||
driver: (process.env.STORAGE_DRIVER as 'local' | 'oss') || 'local',
|
||||
localDir: process.env.STORAGE_LOCAL_DIR || './storage',
|
||||
publicPrefix: process.env.STORAGE_PUBLIC_PREFIX || '/uploads',
|
||||
cdnBaseUrl: process.env.CDN_BASE_URL || '',
|
||||
oss: {
|
||||
endpoint: process.env.OSS_ENDPOINT || '',
|
||||
region: process.env.OSS_REGION || '',
|
||||
bucket: process.env.OSS_BUCKET || '',
|
||||
accessKeyId: process.env.OSS_ACCESS_KEY_ID || '',
|
||||
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET || '',
|
||||
},
|
||||
},
|
||||
blockchain: {
|
||||
driver: (process.env.BLOCKCHAIN_DRIVER as 'mock' | 'tianhe') || 'mock',
|
||||
tianhe: {
|
||||
baseUrl: process.env.TIANHE_BASE_URL || '',
|
||||
appId: process.env.TIANHE_APP_ID || '',
|
||||
appKey: process.env.TIANHE_APP_KEY || '',
|
||||
},
|
||||
},
|
||||
geo: { driver: process.env.GEO_DRIVER || 'mock' },
|
||||
seedAdmin: {
|
||||
username: process.env.SEED_ADMIN_USERNAME || 'admin',
|
||||
password: process.env.SEED_ADMIN_PASSWORD || 'Admin@12345',
|
||||
name: process.env.SEED_ADMIN_NAME || '超级管理员',
|
||||
},
|
||||
logRetentionDays: parseInt(process.env.LOG_RETENTION_DAYS || '365', 10),
|
||||
watermarkText: process.env.WATERMARK_TEXT || '仅供溯源核验使用',
|
||||
};
|
||||
};
|
||||
@@ -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();
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(PrismaService.name);
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.$connect();
|
||||
this.logger.log('数据库已连接');
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user