feat: 搭建 NestJS 后端基础设施与 Prisma 数据模型

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-28 15:35:47 +08:00
co-authored by Cursor
parent 3e9ab08881
commit 9629597b1d
23 changed files with 8051 additions and 0 deletions
@@ -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);
+28
View File
@@ -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 };
}