chore(api): p1a final-review hygiene items
- contracts: add NOT_FOUND error code (framework-level 404 for unknown routes); Error enum + regen committed - api: 404 default mapping in AllExceptionsFilter now NOT_FOUND (was ALBUM_NOT_FOUND); business 404s unchanged via explicit ApiException codes - api: extract configureApp (prefix/CORS/x-powered-by) shared by main-cn bootstrap and e2e; disable x-powered-by, asserted in e2e - api: move parseCursor/parseLimit (+page-size bounds) from albums.controller to shared/pagination; members/uploads/public re-pointed - infra: bind compose published ports to 127.0.0.1 (mysql/redis/minio); .env.example endpoints follow suit - e2e: unknown-route 404 NOT_FOUND + x-powered-by absent cases added (api e2e 120 -> 122) Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -3,8 +3,8 @@
|
||||
// listAlbums/getAlbum/updateAlbum)。控制器级 SessionGuard:四端点全需认证
|
||||
// (契约均有 bearerAuth、无 security: [] 例外)。职责仅剩:
|
||||
// · 透传认证用户(req.user,守卫挂载);
|
||||
// · 查询参数规整(limit 1..100 整数、cursor 长度),非法 → 400
|
||||
// VALIDATION_FAILED,与 body 校验同一出口;
|
||||
// · 查询参数规整(limit 1..100 整数、cursor 长度)经 shared/pagination
|
||||
// (P1a 终审修缮③迁出本控制器),非法 → 400 VALIDATION_FAILED;
|
||||
// · 权限/可见性→HTTP 映射交由服务层抛 ApiException(404 ALBUM_NOT_FOUND)。
|
||||
import {
|
||||
Body,
|
||||
@@ -22,19 +22,17 @@ import { ErrorCodes } from '@photo/contracts';
|
||||
import { ApiException } from '../api-exception';
|
||||
import type { AuthUser } from '../auth/session.guard';
|
||||
import { AuthenticatedRequest, SessionGuard } from '../auth/session.guard';
|
||||
import { parseCursor, parseLimit } from '../shared/pagination';
|
||||
import {
|
||||
DEFAULT_ALBUM_PAGE_SIZE,
|
||||
MAX_ALBUM_PAGE_SIZE,
|
||||
type AlbumListResponse,
|
||||
type AlbumResponse,
|
||||
AlbumsService,
|
||||
} from './albums.service';
|
||||
import { AlbumCreateRequestDto, AlbumUpdateRequestDto } from './dto';
|
||||
import { MAX_CURSOR_LENGTH } from '../shared/cursor';
|
||||
|
||||
/**
|
||||
* 守卫放行后提取 req.user;防御性兜底(守卫未挂载属装配错误,按未认证拒绝)。
|
||||
* members/categories 控制器(Task 17)复用同一判定,导出。
|
||||
* members/categories/photos/uploads 控制器复用同一判定,导出。
|
||||
*/
|
||||
export function userOf(req: AuthenticatedRequest): AuthUser {
|
||||
if (req.user === undefined) {
|
||||
@@ -47,46 +45,6 @@ export function userOf(req: AuthenticatedRequest): AuthUser {
|
||||
return req.user;
|
||||
}
|
||||
|
||||
/** limit 查询参数:缺省 20,须为 1..100 的十进制整数(契约 bounds)。导出供
|
||||
* members 列表(Task 17,同契约 bounds)复用。 */
|
||||
export function parseLimit(raw: string | undefined): number {
|
||||
if (raw === undefined || raw === '') {
|
||||
return DEFAULT_ALBUM_PAGE_SIZE;
|
||||
}
|
||||
if (!/^\d+$/.test(raw)) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
'limit 必须是 1-100 的整数',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
const limit = Number.parseInt(raw, 10);
|
||||
if (limit < 1 || limit > MAX_ALBUM_PAGE_SIZE) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
'limit 必须是 1-100 的整数',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
/** cursor 查询参数:仅做长度规整(语义校验在服务层解码时);导出供 members
|
||||
* 列表(Task 17)复用。 */
|
||||
export function parseCursor(raw: string | undefined): string | undefined {
|
||||
if (raw === undefined || raw === '') {
|
||||
return undefined;
|
||||
}
|
||||
if (raw.length > MAX_CURSOR_LENGTH) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
'cursor 不合法',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
@Controller('albums')
|
||||
@UseGuards(SessionGuard)
|
||||
export class AlbumsController {
|
||||
|
||||
@@ -42,10 +42,6 @@ export type AlbumSummaryResponse = components['schemas']['AlbumSummary'];
|
||||
export type AlbumResponse = components['schemas']['Album'];
|
||||
export type AlbumListResponse = components['schemas']['AlbumList'];
|
||||
|
||||
/** 契约 listAlbums:limit 缺省 20,上下界 1..100。 */
|
||||
export const DEFAULT_ALBUM_PAGE_SIZE = 20;
|
||||
export const MAX_ALBUM_PAGE_SIZE = 100;
|
||||
|
||||
const PUBLIC_TOKEN_LENGTH = 24;
|
||||
const PUBLIC_TOKEN_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// services/api/src/albums/members.controller.ts —— /albums/{albumId}/members
|
||||
// 端点(Task 17)。方法名与契约 operationId 一一对应(addAlbumMember/
|
||||
// listAlbumMembers/removeAlbumMember)。控制器级 SessionGuard:三端点全需
|
||||
// 认证。控制器只做认证用户透传 + 查询参数规整(复用 albums.controller 的
|
||||
// 认证。控制器只做认证用户透传 + 查询参数规整(shared/pagination 的
|
||||
// parseLimit/parseCursor,同一契约 bounds/游标语义);权限与 HTTP 映射由
|
||||
// MembersService 抛 ApiException(404 ALBUM_NOT_FOUND / 403 AUTH_FORBIDDEN /
|
||||
// 409 MEMBER_CONFLICT)。
|
||||
@@ -19,7 +19,8 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthenticatedRequest, SessionGuard } from '../auth/session.guard';
|
||||
import { parseCursor, parseLimit, userOf } from './albums.controller';
|
||||
import { userOf } from './albums.controller';
|
||||
import { parseCursor, parseLimit } from '../shared/pagination';
|
||||
import { MemberAddRequestDto } from './dto';
|
||||
import {
|
||||
type MemberListResponse,
|
||||
|
||||
@@ -51,7 +51,7 @@ describe('AllExceptionsFilter', () => {
|
||||
[new BadRequestException('title is required'), HttpStatus.BAD_REQUEST, ErrorCodes.VALIDATION_FAILED],
|
||||
[new UnauthorizedException(), HttpStatus.UNAUTHORIZED, ErrorCodes.AUTH_TOKEN_EXPIRED],
|
||||
[new ForbiddenException(), HttpStatus.FORBIDDEN, ErrorCodes.AUTH_FORBIDDEN],
|
||||
[new NotFoundException('album'), HttpStatus.NOT_FOUND, ErrorCodes.ALBUM_NOT_FOUND],
|
||||
[new NotFoundException('route'), HttpStatus.NOT_FOUND, ErrorCodes.NOT_FOUND],
|
||||
])('maps HttpException %p to status %i / code %s', (exception, status, code) => {
|
||||
const captured = runFilter(exception, 'req-1');
|
||||
expect(captured.status).toBe(status);
|
||||
|
||||
@@ -28,7 +28,10 @@ const STATUS_TO_ERROR_CODE: Readonly<Record<number, ErrorCode>> = {
|
||||
[HttpStatus.BAD_REQUEST]: ErrorCodes.VALIDATION_FAILED,
|
||||
[HttpStatus.UNAUTHORIZED]: ErrorCodes.AUTH_TOKEN_EXPIRED,
|
||||
[HttpStatus.FORBIDDEN]: ErrorCodes.AUTH_FORBIDDEN,
|
||||
[HttpStatus.NOT_FOUND]: ErrorCodes.ALBUM_NOT_FOUND,
|
||||
// 框架级 404(未注册路由):NOT_FOUND。业务 404(相册/照片不存在等)全部经
|
||||
// ApiException 显式携带域码(ALBUM_NOT_FOUND 等),不走本兜底行——P1a 终审
|
||||
// 修缮①:此前默认 ALBUM_NOT_FOUND 让未知路由冒充业务错误。
|
||||
[HttpStatus.NOT_FOUND]: ErrorCodes.NOT_FOUND,
|
||||
};
|
||||
|
||||
const GENERIC_INTERNAL_MESSAGE = 'Internal server error';
|
||||
|
||||
@@ -2,23 +2,18 @@
|
||||
// cn-app 部署入口(P1a 仅此一个 API 入口)。构建产物 dist/main-cn.js 由根 dev:api /
|
||||
// 生产启动命令运行;env 一律来自进程环境(根 dotenv-cli 注入),此处不读文件。
|
||||
import 'reflect-metadata';
|
||||
import { type INestApplication } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { type NestExpressApplication } from '@nestjs/platform-express';
|
||||
import { Logger } from 'nestjs-pino';
|
||||
import { AppCnModule } from './app-cn.module';
|
||||
import { API_PREFIX } from './shared/constants';
|
||||
import { configureApp } from './shared/configure-app';
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create<INestApplication>(AppCnModule, {
|
||||
const app = await NestFactory.create<NestExpressApplication>(AppCnModule, {
|
||||
bufferLogs: true,
|
||||
});
|
||||
app.useLogger(app.get(Logger));
|
||||
app.setGlobalPrefix(API_PREFIX);
|
||||
const corsOrigins = (process.env.CORS_ORIGINS ?? 'http://localhost:5173')
|
||||
.split(',')
|
||||
.map((origin) => origin.trim())
|
||||
.filter((origin) => origin !== '');
|
||||
app.enableCors({ origin: corsOrigins });
|
||||
configureApp(app);
|
||||
const port = Number.parseInt(process.env.PORT ?? '', 10) || 8080;
|
||||
await app.listen(port);
|
||||
app.get(Logger).log(`api-cn listening on port ${port}`);
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { ErrorCodes } from '@photo/contracts';
|
||||
import { ApiException } from '../api-exception';
|
||||
import { parseCursor } from '../albums/albums.controller';
|
||||
import { parseCursor } from '../shared/pagination';
|
||||
import {
|
||||
DEFAULT_PUBLIC_PHOTO_PAGE_SIZE,
|
||||
MAX_PUBLIC_PHOTO_PAGE_SIZE,
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// services/api/src/shared/configure-app.ts —— 应用级配置(全局前缀 / CORS /
|
||||
// 响应头),main-cn.ts 生产引导与 e2e 测试装配共用同一函数:此前 e2e 各 spec
|
||||
// 手工镜像 setGlobalPrefix,两处漂移无从守护;收敛为单一来源后,e2e 对
|
||||
// x-powered-by 头的断言才真正落在生产引导路径上(P1a 终审修缮②)。
|
||||
// 参数类型取 NestExpressApplication:disable() 是 Express 适配器特有方法。
|
||||
import type { NestExpressApplication } from '@nestjs/platform-express';
|
||||
import { API_PREFIX } from './constants';
|
||||
|
||||
export function configureApp(app: NestExpressApplication): void {
|
||||
app.setGlobalPrefix(API_PREFIX);
|
||||
// 隐藏 Express x-powered-by 指纹响应头(终审修缮②,e2e 断言之)。
|
||||
app.disable('x-powered-by');
|
||||
const corsOrigins = (process.env.CORS_ORIGINS ?? 'http://localhost:5173')
|
||||
.split(',')
|
||||
.map((origin) => origin.trim())
|
||||
.filter((origin) => origin !== '');
|
||||
app.enableCors({ origin: corsOrigins });
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// services/api/src/shared/pagination.ts —— 列表查询参数规整(limit/cursor)。
|
||||
// P1a 终审修缮③:自 albums.controller 迁入 shared——members/uploads/public 与
|
||||
// albums 共用同一契约 bounds,工具函数不再寄居相册控制器导出。语义零变化:
|
||||
// · limit:缺省 20,须为 1..100 的十进制整数,非法 → 400 VALIDATION_FAILED
|
||||
// (与 body 校验同一出口);
|
||||
// · cursor:仅长度上限规整(≤512,契约 CursorQuery.maxLength),语义校验在
|
||||
// 服务层解码处(shared/cursor.ts)。
|
||||
// 公开照片列表 bounds 不同(1..60 缺省 30),其 parsePublicPhotoLimit 仍在
|
||||
// public.controller 本地维护,勿混用。
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
import { ErrorCodes } from '@photo/contracts';
|
||||
import { ApiException } from '../api-exception';
|
||||
import { MAX_CURSOR_LENGTH } from './cursor';
|
||||
|
||||
/** 列表 limit 缺省值(albums/members/uploads 各列表契约共用 bounds)。 */
|
||||
export const DEFAULT_PAGE_SIZE = 20;
|
||||
|
||||
/** 列表 limit 上界(1..100,同上)。 */
|
||||
export const MAX_PAGE_SIZE = 100;
|
||||
|
||||
/** limit 查询参数:缺省 20,须为 1..100 的十进制整数(契约 bounds)。 */
|
||||
export function parseLimit(raw: string | undefined): number {
|
||||
if (raw === undefined || raw === '') {
|
||||
return DEFAULT_PAGE_SIZE;
|
||||
}
|
||||
if (!/^\d+$/.test(raw)) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
'limit 必须是 1-100 的整数',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
const limit = Number.parseInt(raw, 10);
|
||||
if (limit < 1 || limit > MAX_PAGE_SIZE) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
'limit 必须是 1-100 的整数',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
/** cursor 查询参数:仅做长度规整(语义校验在服务层解码时)。 */
|
||||
export function parseCursor(raw: string | undefined): string | undefined {
|
||||
if (raw === undefined || raw === '') {
|
||||
return undefined;
|
||||
}
|
||||
if (raw.length > MAX_CURSOR_LENGTH) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
'cursor 不合法',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
// services/api/src/uploads/uploads.controller.ts —— /uploads 端点(Task 18 起;
|
||||
// Task 19 增补 listUploads/renewUploadCredential/completeUpload)。方法名与契约
|
||||
// operationId 一一对应。控制器级 SessionGuard:端点全需认证。职责:透传认证
|
||||
// 用户 + 查询参数规整(parseLimit/parseCursor 复用相册控制器导出,同契约 bounds)。
|
||||
// 用户 + 查询参数规整(parseLimit/parseCursor 用 shared/pagination,同契约 bounds)。
|
||||
// 注意 DTO 必须值导入(非 import type):@Body 参数类型经 emitDecoratorMetadata
|
||||
// 进入设计期元数据,import type 会令参数在管线中被置为 undefined(Task 18 实测)。
|
||||
import {
|
||||
@@ -16,11 +16,8 @@ import {
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
parseCursor,
|
||||
parseLimit,
|
||||
userOf,
|
||||
} from '../albums/albums.controller';
|
||||
import { userOf } from '../albums/albums.controller';
|
||||
import { parseCursor, parseLimit } from '../shared/pagination';
|
||||
import { AuthenticatedRequest, SessionGuard } from '../auth/session.guard';
|
||||
import { UploadsService } from './uploads.service';
|
||||
import type {
|
||||
|
||||
Reference in New Issue
Block a user