feat(ov): public read api on replicas with hot sorting
P2 Task 6(ov 公开读 API + viewer 切换):
- ov 装配 PublicOvModule(仅 app-ov.module):/public/albums/{token}、
/photos、/photos/{id} 三端点同契约读 ov 副本——translations/categories
自 JSON 列解析(防御性过滤),banner 经 ov 侧 STORAGE_PORT_OV 预签名
(同本地 MinIO;只读属约定,真实 OSS 只读凭证 P5),viewCount 取
album_stats 权威累计(无行默认 0;计数端点 Task 8 接线)
- 排序:latest=发布时间 keyset(shared/cursor.ts 同 cn);hot=likeTotal
desc + photoId desc 决胜,顺序按 `${albumId}|${category}` 短期快照
(内存 TTL 默认 30s,HOT_SORT_TTL_MS 惰性读取)——计数逐请求现读、
顺序冻结窗口内一致,偏移游标(base64url 整数)在快照内严格稳定;
非法 sort 400 VALIDATION_FAILED(cn 不感知该参数)
- 契约:viewCount 放宽为 integer|null(cn null、ov 权威值);
listPublicPhotos 增 sort 枚举(latest|hot,缺省 latest);
PhotoPublishedPayload 增 categoryId——补上 Tasks 3/4 管线缺口
(payloads/publish.service/sync-inbox 投影 + 关联测试随改)
- e2e(services/api/test/public-ov.e2e-spec.ts,7 用例):双入口同进程
起 cn+ov,cn API 种子→真实发送管线投递;断言相册/列表/单图与 cn
深等(仅签名 URL 剔除)、banner 真字节、参数矩阵 400/404、hot 排序
TTL 内快照(计数新/顺序旧)+TTL 过期翻转+偏移翻页、隐藏/下线/紧急
停用逐态撤下
- viewer 切 ov:API 基址 VITE_API_BASE(缺省 http://127.0.0.1:8081,
空串=同源网关;Vite 只读 apps/viewer/.env*,根 .env 对前端无效),
移除 /v1 dev 代理(CORS_ORIGINS 增 127.0.0.1:5175 直连两形);
playwright webServer 增 dev:ov;e2e 夹具 flushSync(albumId)=cn
bootstrap 快照 + deliverPendingOnce(sender 新导出)经真实管线投影
种子,deleteSeededPhoto 改软删让墓碑可同步;14 个 Playwright 全绿
(journey 管理/staffB 腿仍走 cn 8080)
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -1,14 +1,16 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import {
|
||||
cleanupSeededAlbums,
|
||||
flushSync,
|
||||
makePublicToken,
|
||||
seedAlbum,
|
||||
seedBannerAsset,
|
||||
seedCategory,
|
||||
} from './helpers';
|
||||
|
||||
// Task 6 活动页 Playwright(真实后端:API 8080 由 playwright.config webServer 拉起
|
||||
// 或复用已在跑的实例;种子走 Prisma/MinIO 直种,见 helpers.ts)。
|
||||
// Task 6 活动页 Playwright(真实后端:cn API 8080 + ov API 8081 由
|
||||
// playwright.config webServer 拉起或复用已在跑的实例;种子走 Prisma/MinIO 直种
|
||||
// cn 侧,再 flushSync 经真实管线投影到 ov——viewer 已切 ov 读,见 helpers.ts)。
|
||||
// 语言前置:无头 Chromium 默认 en-US——用 addInitScript 预置 localStorage,避免
|
||||
// 依赖浏览器语言;zh 断言由此确定性地落在 zh-CN UI。
|
||||
|
||||
@@ -35,6 +37,7 @@ test('renders album info in zh with timezone-adjusted time, chips and empty stat
|
||||
{ locale: 'en', name: 'Check-in Wall' },
|
||||
]);
|
||||
await seedCategory(album.id, 1, [{ locale: 'zh-CN', name: '开场' }]);
|
||||
await flushSync(album.id);
|
||||
|
||||
await page.addInitScript(() => localStorage.setItem('viewer.locale', 'zh-CN'));
|
||||
await page.goto(`/a/${album.publicToken}`);
|
||||
@@ -66,6 +69,7 @@ test('switching locale re-fetches and shows the English translation', async ({ p
|
||||
{ locale: 'en', title: 'Bilingual Test Album', description: 'English intro', venue: 'Main Hall' },
|
||||
],
|
||||
});
|
||||
await flushSync(album.id);
|
||||
|
||||
await page.addInitScript(() => localStorage.setItem('viewer.locale', 'zh-CN'));
|
||||
await page.goto(`/a/${album.publicToken}`);
|
||||
@@ -84,6 +88,7 @@ test('en UI with a zh-only album falls back to zh content while chrome stays en'
|
||||
alias: 'fallback',
|
||||
translations: [{ locale: 'zh-CN', title: '只有中文的相册', venue: '大宴会厅' }],
|
||||
});
|
||||
await flushSync(album.id);
|
||||
|
||||
await page.addInitScript(() => localStorage.setItem('viewer.locale', 'en'));
|
||||
await page.goto(`/a/${album.publicToken}`);
|
||||
@@ -101,6 +106,7 @@ test('banner signed URL loads a real image', async ({ page }) => {
|
||||
translations: [{ locale: 'zh-CN', title: '有封面的相册' }],
|
||||
});
|
||||
await seedBannerAsset(album.id);
|
||||
await flushSync(album.id);
|
||||
|
||||
await page.addInitScript(() => localStorage.setItem('viewer.locale', 'zh-CN'));
|
||||
await page.goto(`/a/${album.publicToken}`);
|
||||
@@ -119,6 +125,8 @@ test('offline and ghost tokens show the localized unavailable error', async ({ p
|
||||
status: 'offline',
|
||||
translations: [{ locale: 'zh-CN', title: '已下线相册' }],
|
||||
});
|
||||
// 下线态也经真实管线同步:ov 侧 status=offline → isAlbumVisibleOv=false → 404。
|
||||
await flushSync(offline.id);
|
||||
|
||||
await page.addInitScript(() => localStorage.setItem('viewer.locale', 'zh-CN'));
|
||||
await page.goto(`/a/${offline.publicToken}`);
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import { cleanupSeededAlbums, seedAlbum, seedCategory, seedPhoto } from './helpers';
|
||||
import {
|
||||
cleanupSeededAlbums,
|
||||
flushSync,
|
||||
seedAlbum,
|
||||
seedCategory,
|
||||
seedPhoto,
|
||||
} from './helpers';
|
||||
|
||||
// Task 7 瀑布流 Playwright(真实后端):35 张已发布照片(公开列表默认页 30)→
|
||||
// 初始 30 + 滚动取第 2 页 5 张;分类 chips 过滤;新照片轮询提示(__viewerPollMs
|
||||
// 注入缩短间隔,见 PhotoFeed pollIntervalMs 的 dev/test 覆盖钩子)。
|
||||
// 种子直种 cn 侧,seedFeedAlbum/新增照片后 flushSync 投影到 ov(viewer 读 ov)。
|
||||
|
||||
test.afterAll(async () => {
|
||||
await cleanupSeededAlbums();
|
||||
@@ -39,6 +46,7 @@ async function seedFeedAlbum(alias: string): Promise<{ albumId: string; token: s
|
||||
publishedAt: new Date(base - (i + 1) * 60_000),
|
||||
});
|
||||
}
|
||||
await flushSync(album.id);
|
||||
return { albumId: album.id, token: album.publicToken };
|
||||
}
|
||||
|
||||
@@ -109,7 +117,7 @@ test('new-photo poll hint appears; click refreshes to include new photos', async
|
||||
await expect(page.locator('.cell')).toHaveCount(35);
|
||||
await expect(page.locator('.new-photo-bar')).toHaveCount(0);
|
||||
|
||||
// 轮询期间直种 2 张更新的照片(publishedAt 晚于全部既有)。
|
||||
// 轮询期间直种 2 张更新的照片(publishedAt 晚于全部既有)并同步到 ov。
|
||||
const base = Date.now();
|
||||
for (let i = 0; i < 2; i++) {
|
||||
await seedPhoto(albumId, `poll-new-${i}`, {
|
||||
@@ -119,6 +127,7 @@ test('new-photo poll hint appears; click refreshes to include new photos', async
|
||||
publishedAt: new Date(base + (i + 1) * 60_000),
|
||||
});
|
||||
}
|
||||
await flushSync(albumId);
|
||||
|
||||
// 提示条出现(不自动插入——仍 35 张)。
|
||||
await expect(page.locator('.new-photo-bar')).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
// services/api/test/public.e2e-spec.ts 的种子形状)。公开端点匿名可达,无需登录态。
|
||||
// Task 7 起补 seedPhoto:直种「已发布完成态」照片(photos + thumb/browse 变体行
|
||||
// + MinIO 真实 JPEG 对象,行形状同 worker 发布事务落库形态)。
|
||||
// P2 Task 6 起 viewer 读 ov 副本(VITE_API_BASE 直连 8081)——直种只落 cn 库,
|
||||
// 故 seed* 后必须 flushSync(albumId):经 cn bootstrap(当前态快照写回 outbox)
|
||||
// + deliverPendingOnce(真实发送管线排空)把种子投影到 ov 副本,无旁路。
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
@@ -10,6 +13,12 @@ import { config } from 'dotenv';
|
||||
import sharp from 'sharp';
|
||||
import { PrismaClient } from '@photo/db-cn';
|
||||
import { createStorageFromEnv, type MinioStorageAdapter } from '@photo/storage';
|
||||
import {
|
||||
SYNC_SIGNATURE_HEADER,
|
||||
SYNC_TIMESTAMP_HEADER,
|
||||
signSyncBody,
|
||||
} from '@photo/contracts';
|
||||
import { deliverPendingOnce } from '../../../services/sync/src/sender';
|
||||
|
||||
// 仓库根 .env 唯一来源(同 services/api test/load-env.ts 约定)。必须在
|
||||
// PrismaClient / createStorageFromEnv 构造前执行——两者均在首次查询/调用时读 env。
|
||||
@@ -198,11 +207,45 @@ export async function seedPhoto(
|
||||
return photoId;
|
||||
}
|
||||
|
||||
/** 直删照片域行(Task 8 e2e:模拟已分享深链的照片下线——变体行在前、主行在后;
|
||||
* MinIO 对象随 dev 前缀清理约定,不在此删)。 */
|
||||
/** cn→ov 种子同步(P2 Task 6):先打 cn bootstrap(当前态快照事件写回 outbox,
|
||||
* 优先级 normal),再 deliverPendingOnce 经真实发送管线(HMAC 签名
|
||||
* content-batches)排空至 ov 副本。幂等可重入:同版本新 eventId 在 ov 侧按
|
||||
* 当前态重断言应用;与常驻 dev:sync 发送器并发亦安全(eventId 幂等)。 */
|
||||
export async function flushSync(albumId: string): Promise<void> {
|
||||
const internalKey = process.env.SYNC_INTERNAL_KEY ?? 'dev-sync-secret-change-me';
|
||||
const rawBody = JSON.stringify({ albumId });
|
||||
const timestamp = Math.floor(Date.now() / 1000).toString();
|
||||
const cnBase = (process.env.CN_API_URL ?? 'http://127.0.0.1:8080').replace(/\/+$/, '');
|
||||
const bootstrap = await fetch(`${cnBase}/v1/internal/sync/bootstrap`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
[SYNC_TIMESTAMP_HEADER]: timestamp,
|
||||
[SYNC_SIGNATURE_HEADER]: signSyncBody(internalKey, rawBody),
|
||||
},
|
||||
body: rawBody,
|
||||
});
|
||||
if (!bootstrap.ok) {
|
||||
throw new Error(
|
||||
`flushSync bootstrap 失败(${bootstrap.status}):${(await bootstrap.text()).slice(0, 300)}`,
|
||||
);
|
||||
}
|
||||
await deliverPendingOnce({
|
||||
prisma,
|
||||
ovApiUrl: process.env.OV_API_URL ?? 'http://127.0.0.1:8081',
|
||||
internalKey,
|
||||
});
|
||||
}
|
||||
|
||||
/** 模拟已分享深链的照片下线(Task 8 e2e):软删(visibility=deleted +
|
||||
* entityVersion 自增)——硬删会让 cn 行缺席、bootstrap 快照无从发墓碑,ov 副本
|
||||
* 将永远留着旧发布行;软删 + flushSync 让 photo.deleted 事件走真实管线撤下。
|
||||
* 变体行/MinIO 对象保留(公开读只看 photos 行;行清理归 cleanupSeededAlbums)。 */
|
||||
export async function deleteSeededPhoto(photoId: string): Promise<void> {
|
||||
await prisma.photo_variants.deleteMany({ where: { photoId } });
|
||||
await prisma.photos.deleteMany({ where: { id: photoId } });
|
||||
await prisma.photos.update({
|
||||
where: { id: photoId },
|
||||
data: { visibility: 'deleted', entityVersion: { increment: 1 } },
|
||||
});
|
||||
}
|
||||
|
||||
/** 清理本文件种下的相册域行(扁平字符串外键、无 DB 级联——按子表在前手工删;
|
||||
@@ -223,6 +266,11 @@ export async function cleanupSeededAlbums(): Promise<void> {
|
||||
});
|
||||
}
|
||||
await prisma.photos.deleteMany({ where: { albumId: { in: seededAlbumIds } } });
|
||||
// flushSync 经 outbox 投递的快照事件行(已投递/未投递一并清——未投递
|
||||
// 残留会污染后续 deliverPendingOnce 的排空判定轮次)。
|
||||
await prisma.outbox_events.deleteMany({
|
||||
where: { albumId: { in: seededAlbumIds } },
|
||||
});
|
||||
const categories = await prisma.categories.findMany({
|
||||
where: { albumId: { in: seededAlbumIds } },
|
||||
select: { id: true },
|
||||
|
||||
@@ -12,6 +12,9 @@
|
||||
// ④ admin UI 再登录:照片管理 3 行(就绪/已发布)→ 隐藏 1 张 → viewer 重载
|
||||
// 剩 2 张 → 被隐深链 404 本地化提示;
|
||||
// ⑤ 空相册 B(admin API 建,无照片):viewer 空态提示「照片即将上线」。
|
||||
// P2 Task 6 起 viewer 观众腿读 ov 副本(VITE_API_BASE 直连 8081)——本剧本的
|
||||
// cn 侧变更(发布/隐藏/建 B 相册)在各 viewer 腿前 flushSync(bootstrap 快照 +
|
||||
// 真实发送管线排空)投影到 ov;admin/staffB 腿仍走 cn 8080(代理/直连,不变)。
|
||||
// 数据清理:afterAll 按 viewer helpers 同序直删(含 album_members/upload_sessions/
|
||||
// photo_jobs/outbox_events 等 API 链路落库行)+ staffB 账号域行。
|
||||
import { randomBytes } from 'node:crypto';
|
||||
@@ -25,6 +28,7 @@ import { createStorageFromEnv, type MinioStorageAdapter } from '@photo/storage';
|
||||
import { hashPassword } from '../../../services/api/src/auth/password';
|
||||
import { seedAdmin } from '../../../services/api/src/scripts/seed-admin';
|
||||
import { PublishService } from '../../../services/worker/src/publish.service';
|
||||
import { flushSync } from './helpers';
|
||||
|
||||
// 仓库根 .env 唯一来源(同 helpers.ts 约定):PrismaClient/createStorageFromEnv
|
||||
// 构造前先加载。API 腿直连 8080(服务端到服务端,无 CORS 面)。
|
||||
@@ -92,6 +96,7 @@ test.describe.serial('cross-frontend journey (admin → api/worker → viewer)',
|
||||
let adminToken: string;
|
||||
let albumId: string;
|
||||
let publicToken: string;
|
||||
let emptyAlbumId: string;
|
||||
let emptyToken: string;
|
||||
let categoryId: string;
|
||||
const photoIds: string[] = [];
|
||||
@@ -284,7 +289,8 @@ test.describe.serial('cross-frontend journey (admin → api/worker → viewer)',
|
||||
},
|
||||
});
|
||||
expect(emptyAlbum.status).toBe(201);
|
||||
journeyAlbumIds.push(emptyAlbum.json.id as string);
|
||||
emptyAlbumId = emptyAlbum.json.id as string;
|
||||
journeyAlbumIds.push(emptyAlbumId);
|
||||
emptyToken = emptyAlbum.json.publicToken as string;
|
||||
|
||||
// ── ② staffB API:登录 → init×3 → presign PUT 实写 → complete×3 ──
|
||||
@@ -363,6 +369,10 @@ test.describe.serial('cross-frontend journey (admin → api/worker → viewer)',
|
||||
expect(items).toHaveLength(3);
|
||||
expect(new Set(items.map((p) => p.photoId))).toEqual(new Set(photoIds));
|
||||
|
||||
// cn→ov:发布事实经真实管线投影(album/banner/分类/3 张照片快照入 outbox
|
||||
// 并排空投递)——viewer 腿读 ov 副本,此后才可见。
|
||||
await flushSync(albumId);
|
||||
|
||||
// ── ③ viewer UI:zh 打开 → banner 渲染 → 切 en 内容随切 → 回 zh ──
|
||||
await page.addInitScript(() => localStorage.setItem('viewer.locale', 'zh-CN'));
|
||||
await page.goto(`/a/${publicToken}`);
|
||||
@@ -446,6 +456,9 @@ test.describe.serial('cross-frontend journey (admin → api/worker → viewer)',
|
||||
await page.getByRole('button', { name: '确定' }).click();
|
||||
await expect(targetRow.getByTestId('photo-visibility-tag')).toHaveText('已隐藏');
|
||||
|
||||
// 隐藏事实同步到 ov(viewer 下一腿的重载/深链 404 断言读 ov 副本)。
|
||||
await flushSync(albumId);
|
||||
|
||||
// ── ④ viewer:重载列表变 2 → 被隐深链 404 本地化提示 ──
|
||||
await page.goto(`/a/${publicToken}`);
|
||||
await expect(page.locator('.cell')).toHaveCount(2);
|
||||
@@ -455,7 +468,8 @@ test.describe.serial('cross-frontend journey (admin → api/worker → viewer)',
|
||||
await expect(notice).toContainText('照片不存在或已下线');
|
||||
await expect(page.locator('.lightbox')).toHaveCount(0);
|
||||
|
||||
// ── ⑤ 空相册 B:viewer 空态提示 ──
|
||||
// ── ⑤ 空相册 B:viewer 空态提示(B 经 API 建于 cn,先同步到 ov)──
|
||||
await flushSync(emptyAlbumId);
|
||||
await page.goto(`/a/${emptyToken}`);
|
||||
await expect(page.locator('.empty-notice')).toHaveText('照片即将上线');
|
||||
await expect(page.locator('.cell')).toHaveCount(0);
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import { cleanupSeededAlbums, deleteSeededPhoto, seedAlbum, seedPhoto } from './helpers';
|
||||
import {
|
||||
cleanupSeededAlbums,
|
||||
deleteSeededPhoto,
|
||||
flushSync,
|
||||
seedAlbum,
|
||||
seedPhoto,
|
||||
} from './helpers';
|
||||
|
||||
// Task 8 大图查看器 Playwright(真实后端):点击开大图(browse 经签名 URL 取回
|
||||
// 真实字节)→ 左右切换保持列表序列 → 滚轮缩放(受控 transform)→ 关闭回原滚动
|
||||
// 位置 → 深链直达(单图先行 + 背后列表构成序列)→ 404 深链本地化提示 → 越过
|
||||
// 末页边界的导航扩展序列。
|
||||
// 末页边界的导航扩展序列。种子直种 cn 侧后 flushSync 投影到 ov(viewer 读 ov)。
|
||||
|
||||
test.afterAll(async () => {
|
||||
await cleanupSeededAlbums();
|
||||
@@ -19,8 +25,11 @@ const RATIOS: Array<{ width: number; height: number }> = [
|
||||
];
|
||||
|
||||
/** 种「查看器相册」:count 张已发布照片,publishedAt 逐张递减 60s(列表顺序确定)。
|
||||
* 返回 token 与按列表顺序排列的 photoId。 */
|
||||
async function seedViewerAlbum(alias: string, count: number): Promise<{ token: string; photoIds: string[] }> {
|
||||
* 返回 token 与按列表顺序排列的 photoId。种子后 flushSync 投影到 ov。 */
|
||||
async function seedViewerAlbum(
|
||||
alias: string,
|
||||
count: number,
|
||||
): Promise<{ albumId: string; token: string; photoIds: string[] }> {
|
||||
const album = await seedAlbum({
|
||||
alias,
|
||||
translations: [{ locale: 'zh-CN', title: '大图查看测试相册' }],
|
||||
@@ -37,7 +46,8 @@ async function seedViewerAlbum(alias: string, count: number): Promise<{ token: s
|
||||
}),
|
||||
);
|
||||
}
|
||||
return { token: album.publicToken, photoIds };
|
||||
await flushSync(album.id);
|
||||
return { albumId: album.id, token: album.publicToken, photoIds };
|
||||
}
|
||||
|
||||
async function openLocale(page: Page, token: string, path = ''): Promise<void> {
|
||||
@@ -135,9 +145,11 @@ test('deep link opens on the target photo with the list loaded behind', async ({
|
||||
|
||||
test('deep link to a removed photo shows the localized notice and a working back link', async ({ page }) => {
|
||||
test.setTimeout(90_000);
|
||||
const { token, photoIds } = await seedViewerAlbum('viewer-404', 2);
|
||||
const { token, albumId, photoIds } = await seedViewerAlbum('viewer-404', 2);
|
||||
const gone = photoIds[1]!;
|
||||
await deleteSeededPhoto(gone); // 模拟照片已下线(旧分享链接)
|
||||
// 模拟照片已下线(旧分享链接):软删 + flushSync 让墓碑走真实管线撤下 ov 副本。
|
||||
await deleteSeededPhoto(gone);
|
||||
await flushSync(albumId);
|
||||
|
||||
await openLocale(page, token, `/p/${gone}`);
|
||||
const notice = page.locator('.deep-link-notice');
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
// Task 6 起 e2e 打真实后端:webServer 先等 API(8080,仓库根 `pnpm dev:api`
|
||||
// 构建+启动;已在跑的实例直接复用),再等 viewer dev(5175,/v1 代理 → 8080)。
|
||||
// compose 基础设施(MySQL/MinIO/Redis)需预先 `docker compose up -d`(计划约定)。
|
||||
// Task 11 起跨端联调:第三个 webServer 一并等 admin dev(5176,/v1 代理 → 8080,
|
||||
// 同样复用已在跑的实例)——journey.spec.ts 以绝对 baseURL 驱动 admin 腿。
|
||||
// Task 6 起 e2e 打真实后端:webServer 先等 cn API(8080,仓库根 `pnpm dev:api`
|
||||
// 构建+启动;已在跑的实例直接复用;journey 管理/上传腿与 flushSync 的
|
||||
// bootstrap 触发仍走 cn),再等 ov API(8081,`pnpm dev:ov`——P2 Task 6 起
|
||||
// viewer 观众腿全部切 ov 副本端点),再等 viewer dev(5175,直连
|
||||
// VITE_API_BASE=ov 8081,无代理)。compose 基础设施(MySQL/MinIO/Redis×2)
|
||||
// 需预先 `docker compose up -d`(计划约定)。Task 11 起跨端联调:第四个
|
||||
// webServer 一并等 admin dev(5176,/v1 代理 → 8080,同样复用已在跑的实例)
|
||||
// ——journey.spec.ts 以绝对 baseURL 驱动 admin 腿。
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
timeout: 30_000,
|
||||
@@ -23,6 +26,13 @@ export default defineConfig({
|
||||
reuseExistingServer: true,
|
||||
timeout: 180_000, // 首次含 tsc 全量构建
|
||||
},
|
||||
{
|
||||
command: 'pnpm dev:ov',
|
||||
cwd: '../..',
|
||||
url: 'http://127.0.0.1:8081/v1/health',
|
||||
reuseExistingServer: true,
|
||||
timeout: 180_000, // 复用同一构建产物,首次仍可能全量构建
|
||||
},
|
||||
{
|
||||
command: 'pnpm run dev',
|
||||
url: 'http://127.0.0.1:5175',
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ApiError, NETWORK_ERROR_CODE, getPublicAlbum, getPublicPhotos } from '../api/client';
|
||||
import {
|
||||
ApiError,
|
||||
DEFAULT_API_BASE,
|
||||
NETWORK_ERROR_CODE,
|
||||
apiBase,
|
||||
getPublicAlbum,
|
||||
getPublicPhotos,
|
||||
} from '../api/client';
|
||||
import { errorMessageKey } from '../api/errors';
|
||||
|
||||
function jsonResponse(status: number, body: unknown): Response {
|
||||
@@ -8,6 +15,37 @@ function jsonResponse(status: number, body: unknown): Response {
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe('api base url', () => {
|
||||
it('defaults to the ov entry (8081) when VITE_API_BASE is unset', () => {
|
||||
expect(apiBase()).toBe(DEFAULT_API_BASE);
|
||||
expect(DEFAULT_API_BASE).toBe('http://127.0.0.1:8081');
|
||||
});
|
||||
|
||||
it('uses VITE_API_BASE when the build provides one', () => {
|
||||
vi.stubEnv('VITE_API_BASE', 'https://api.example.com');
|
||||
expect(apiBase()).toBe('https://api.example.com');
|
||||
});
|
||||
|
||||
it('treats empty string as same-origin (production gateway deploy)', () => {
|
||||
// 空串非 nullish:?? 不回退缺省,fetch 得到相对 /v1 路径(同源网关)。
|
||||
vi.stubEnv('VITE_API_BASE', '');
|
||||
expect(apiBase()).toBe('');
|
||||
});
|
||||
|
||||
it('requests go to the configured base + /v1 path', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200, { items: [], nextCursor: null }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
vi.stubEnv('VITE_API_BASE', 'https://api.example.com');
|
||||
|
||||
await getPublicPhotos('tok-1');
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'https://api.example.com/v1/public/albums/tok-1/photos',
|
||||
expect.objectContaining({}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('api client', () => {
|
||||
@@ -20,7 +58,7 @@ describe('api client', () => {
|
||||
const album = await getPublicAlbum('tok-1', 'zh-CN');
|
||||
expect(album.publicToken).toBe('tok-1');
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/v1/public/albums/tok-1?locale=zh-CN',
|
||||
`${DEFAULT_API_BASE}/v1/public/albums/tok-1?locale=zh-CN`,
|
||||
expect.objectContaining({ headers: expect.objectContaining({ accept: 'application/json' }) }),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -42,11 +42,23 @@ function parseErrorEnvelope(body: unknown): { code: string | null; message: stri
|
||||
return { code: null, message: null, requestId: null };
|
||||
}
|
||||
|
||||
// P2 Task 6:API 基址可配(VITE_API_BASE)。dev 缺省直连 ov 入口(127.0.0.1:8081,
|
||||
// 观众域切换海外副本——契约路径不变,仅部署域名区分);生产同源网关部署时构建期
|
||||
// 置 VITE_API_BASE=""(空串 → 同源相对路径)。注意 Vite 只读 apps/viewer/.env*,
|
||||
// 仓库根 .env 对前端无效(缺省值即 dev 指向 ov)。直连跨源依赖 API 侧
|
||||
// CORS_ORIGINS 包含 viewer origin(根 .env 已含 5175 的 localhost/127.0.0.1 两形)。
|
||||
export const DEFAULT_API_BASE = 'http://127.0.0.1:8081';
|
||||
|
||||
/** 逐请求读取(惰性):测试可 stub import.meta.env 覆盖。 */
|
||||
export function apiBase(): string {
|
||||
return import.meta.env.VITE_API_BASE ?? DEFAULT_API_BASE;
|
||||
}
|
||||
|
||||
/** 类型化 fetch 封装:统一前缀 /v1、JSON 解析、错误信封 → ApiError。 */
|
||||
export async function apiRequest<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`/v1${path}`, {
|
||||
response = await fetch(`${apiBase()}/v1${path}`, {
|
||||
...init,
|
||||
headers: { accept: 'application/json', ...init?.headers },
|
||||
});
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
// dev server 固定 5175(CORS_ORIGINS 已包含);/v1 代理仅作用于 `vite dev`,
|
||||
// build/preview 不经此处——生产由网关同源挂载 /v1。
|
||||
// host 显式 127.0.0.1:Windows 下 localhost 默认可能只绑 [::1],代理/e2e 探活走 IPv4。
|
||||
// dev server 固定 5175。P2 Task 6 起不再代理 /v1:前端直连 VITE_API_BASE
|
||||
// (缺省 ov 入口 127.0.0.1:8081,见 src/api/client.ts)——跨源访问由 API 侧
|
||||
// CORS_ORIGINS 放行(根 .env 含 5175 的 localhost/127.0.0.1 两形);admin 入口
|
||||
// (5176)仍各自代理 /v1 → cn 8080(journey 管理腿不走此处)。
|
||||
// host 显式 127.0.0.1:Windows 下 localhost 默认可能只绑 [::1],e2e 探活走 IPv4。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
server: {
|
||||
host: '127.0.0.1',
|
||||
port: 5175,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/v1': { target: 'http://127.0.0.1:8080', changeOrigin: true },
|
||||
},
|
||||
},
|
||||
preview: { host: '127.0.0.1', port: 5175, strictPort: true },
|
||||
test: {
|
||||
|
||||
Reference in New Issue
Block a user