feat: V1.1 批次入库——色号表SEO页/Showcase/图纸库/帮助中心/JSON-LD/CI门禁/竞品分析

This commit is contained in:
Sisyphus committed 2026-08-15 14:41:00 +08:00
1 parent 40e2342a02
commit f53f0a2b25
104 files changed
+21760 -157

No files matched your search

+190
View File
@@ -0,0 +1,190 @@
/**
* 色号表 SEO 页面 JSON-LD 结构化数据 API。
*
* 设计说明(SPA 无 SSR 的注入方案):
* 1. 本项目是纯前端 SPA(Vite),没有 SSR 可以在页面源码中直接输出
* <script type="application/ld+json">。因此采用「后端数据接口 + 前端注入」:
* 后端提供 GET /api/color-chart/:brand 返回该品牌色号表的 JSON-LD
* (schema.org CollectionPage + ItemList),前端色号表路由页加载后把
* 返回值序列化注入 <script type="application/ld+json"> 即可让搜索引擎
* 识别该页面的结构化数据。
* 2. 数据来源:D:\拼豆\competitor-analysis\palettes\ 下的品牌色板 JSON
* (只读)。mard 使用 291 标准色映射(hex → {MARD: 色号, ...}),
* 其余品牌使用各自 {code, hex, rgb, name} 数组文件:
* mard → zippland-291标准色映射.json
* artkal-c → artkal-c.json
* perler → perler.json
* hama → hama.json
* pyssla → ikea-pyssla.json
* nabbi → nabbi.json
* 3. 文件在模块加载时读取一次(非每请求读取);读取失败时告警并回退为空
* 列表(不阻断服务启动,与 palettes 模块行为一致)。
*/
import { readFileSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { Router } from "express";
import type { Request, Response } from "express";
/** 单个色号条目(JSON-LD ListItem 的 item 部分)。 */
export interface ChartColor {
code: string;
hex: string;
name: string;
}
/** 品牌色号表数据。 */
export interface BrandChart {
id: string;
name: string;
colors: ChartColor[];
}
/** 品牌定义:id / 展示名 / 数据文件 / 文件类型。 */
interface BrandDef {
id: string;
name: string;
fileName: string;
/** true 表示 hex → {品牌: 色号} 映射对象;false 表示 {code,hex,rgb,name} 数组。 */
mapping: boolean;
/** 映射文件中该品牌对应的键(仅 mapping=true 时使用,如 zippland 映射里是 "MARD")。 */
mappingKey?: string;
}
/** 色号表品牌注册表(前端路由 /color-chart/:brand 的 slug 对齐)。 */
const BRAND_DEFS: readonly BrandDef[] = [
{ id: "mard", name: "MARD 玛德", fileName: "zippland-291标准色映射.json", mapping: true, mappingKey: "MARD" },
{ id: "artkal-c", name: "Artkal C", fileName: "artkal-c.json", mapping: false },
{ id: "perler", name: "Perler", fileName: "perler.json", mapping: false },
{ id: "hama", name: "Hama", fileName: "hama.json", mapping: false },
{ id: "pyssla", name: "IKEA Pyssla", fileName: "ikea-pyssla.json", mapping: false },
{ id: "nabbi", name: "Nabbi", fileName: "nabbi.json", mapping: false },
];
/** 色板 JSON 默认目录:仓库根 D:\拼豆\competitor-analysis\palettes\。 */
const DEFAULT_PALETTES_DIR = resolve(
dirname(fileURLToPath(import.meta.url)),
"../../..",
"competitor-analysis",
"palettes",
);
/** hex 格式校验(映射文件 key)。 */
const HEX_RE = /^#[0-9A-Fa-f]{6}$/;
/**
* 从 hex→{品牌:色号} 映射对象派生品牌色号列表。
* 仅纳入映射中存在该品牌色号、且 hex 合法的条目;按映射顺序输出。
*/
function deriveFromMapping(raw: unknown, mappingKey: string): ChartColor[] {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return [];
}
const colors: ChartColor[] = [];
for (const [hex, entry] of Object.entries(raw as Record<string, Record<string, string>>)) {
if (!HEX_RE.test(hex)) continue;
const code = entry?.[mappingKey];
if (typeof code === "string" && code.trim() !== "") {
colors.push({ code: code.trim(), hex: hex.toUpperCase(), name: code.trim() });
}
}
return colors;
}
/** 从 {code, hex, rgb, name} 数组派生品牌色号列表。 */
function deriveFromArray(raw: unknown): ChartColor[] {
if (!Array.isArray(raw)) return [];
const colors: ChartColor[] = [];
for (const entry of raw) {
if (typeof entry !== "object" || entry === null) continue;
const { code, hex, name } = entry as { code?: unknown; hex?: unknown; name?: unknown };
if (typeof code !== "string" || code.trim() === "") continue;
if (typeof hex !== "string" || !HEX_RE.test(hex)) continue;
const label = typeof name === "string" && name.trim() !== "" ? name.trim() : code.trim();
colors.push({ code: code.trim(), hex: hex.toUpperCase(), name: label });
}
return colors;
}
/** 加载单个品牌色号表(模块加载时执行一次)。 */
function loadBrandChart(def: BrandDef): BrandChart {
const dir = process.env["PALETTES_DIR"] ?? DEFAULT_PALETTES_DIR;
const filePath = resolve(dir, def.fileName);
let raw: unknown;
try {
raw = JSON.parse(readFileSync(filePath, "utf8"));
} catch (err) {
console.warn(`[color-chart] 无法读取品牌色板文件(${filePath}):${(err as Error).message}`);
return { id: def.id, name: def.name, colors: [] };
}
const colors = def.mapping
? deriveFromMapping(raw, def.mappingKey ?? def.id)
: deriveFromArray(raw);
return { id: def.id, name: def.name, colors };
}
/** 模块加载时读取一次全部品牌色号表。 */
const CHARTS: ReadonlyMap<string, BrandChart> = new Map(
BRAND_DEFS.map((def) => [def.id, loadBrandChart(def)]),
);
/**
* 组装 JSON-LD:CollectionPage 包裹 ItemList。
* - 顶层 CollectionPage:提供页面级 name / url / description。
* - mainEntity ItemList:提供 numberOfItems 与逐项 itemListElement(ListItem,
* 每个 item 为 Product,携带 identifier=色号、name=色名/色号、color=hex)。
*/
export function buildJsonLd(chart: BrandChart): Record<string, unknown> {
return {
"@context": "https://schema.org",
"@type": "CollectionPage",
name: `${chart.name} 拼豆色号表`,
url: `/color-chart/${chart.id}`,
description: `${chart.name} 拼豆品牌色号对照表,共 ${chart.colors.length} 个颜色。`,
mainEntity: {
"@type": "ItemList",
name: `${chart.name} 拼豆色号表`,
numberOfItems: chart.colors.length,
itemListElement: chart.colors.map((color, index) => ({
"@type": "ListItem",
position: index + 1,
item: {
"@type": "Product",
name: color.name,
identifier: color.code,
color: color.hex,
brand: {
"@type": "Brand",
name: chart.name,
},
},
})),
},
};
}
/**
* 创建色号表 JSON-LD 路由。
*
* GET /api/color-chart/:brand
* 200 → { "@context": "https://schema.org", "@type": "CollectionPage", ... }
* 404 → { error: "品牌不存在" }
*/
export function createColorChartRouter(): Router {
const router = Router();
router.get("/:brand", (req: Request, res: Response): void => {
const raw = req.params["brand"];
const brandId = typeof raw === "string" ? raw : "";
const chart = CHARTS.get(brandId);
if (chart === undefined) {
res.status(404).json({ error: "品牌不存在" });
return;
}
res.setHeader("Content-Type", "application/ld+json; charset=utf-8");
res.status(200).json(buildJsonLd(chart));
});
return router;
}
+15
View File
@@ -106,4 +106,19 @@ CREATE TABLE IF NOT EXISTS download_grants (
-- 索引:按兑换码查询下载授权
CREATE INDEX IF NOT EXISTS idx_download_grants_code ON download_grants(code);
-- chibi Showcase 作品表
-- title: 作品标题;image_data: base64 dataURL 或 http(s) URL;
-- tags: 标签数组 JSON 文本(如 '["宠物","猫"]');source: 作品来源(如 chibi/manual)
CREATE TABLE IF NOT EXISTS showcase_works (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
image_data TEXT NOT NULL,
tags TEXT NOT NULL DEFAULT '[]',
source TEXT NOT NULL DEFAULT 'manual',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
-- 索引:按创建时间倒序查询作品列表(Showcase 展示页主路径)
CREATE INDEX IF NOT EXISTS idx_showcase_works_created_at ON showcase_works(created_at DESC, id DESC);
`;
+4
View File
@@ -8,6 +8,8 @@ import { createChibiRouter } from "./chibi/routes.js";
import { createSyncRouter } from "./sync/routes.js";
import { createPalettesRouter } from "./palettes/routes.js";
import { createExportRouter } from "./export/routes.js";
import { createColorChartRouter } from "./color-chart/routes.js";
import { createShowcaseRouter } from "./showcase/routes.js";
const PORT = parseInt(process.env["PORT"] ?? "8788", 10);
@@ -64,6 +66,8 @@ export function createApp(db?: Database.Database): Express {
app.use("/api/sync", createSyncRouter(db));
app.use("/api/palettes", createPalettesRouter());
app.use("/api/export", createExportRouter());
app.use("/api/color-chart", createColorChartRouter());
app.use("/api/showcase", createShowcaseRouter(db));
// ---- 404 handler ----
app.use((_req, res) => {
+276
View File
@@ -0,0 +1,276 @@
/**
* chibi Showcase 作品 API。
*
* POST /api/showcase/works(T-099 发布接口)
* Request: { title: string, imageData: string, tags?: string[], source?: string }
* Response: 201 { id: number }
* 400 { error: "请输入作品标题" } 标题为空
* 400 { error: "作品标题过长" } 标题超过 100 字符
* 400 { error: "图片格式无效" } imageData 非 base64 dataURL 也非 http(s) URL
* 400 { error: "标签格式无效" } tags 不是数组
* 500 服务器内部错误
*
* GET /api/showcase/works(T-100 展示页列表)
* Query: page=1&limit=12&tag=卡通动漫&source=chibi
* Response: 200 { items: [{ id, title, imageUrl, tags, source, createdAt }],
* total, page, limit }(items 按 created_at DESC, id DESC)
* 400 { error: "分页参数无效" } page/limit 非正整数
*
* GET /api/showcase/meta(T-101 展示页 SEO 元数据)
* Query: lang=zh|en(缺省 zh)
* Response: 200 { title, description, ogImage, jsonLd }
*/
import { Router } from "express";
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import { getDb } from "../db/index.js";
import { insertWork, type ShowcaseWorkRow } from "./service.js";
/** 标题最大长度。 */
const MAX_TITLE_LENGTH = 100;
/** 标签最大数量。 */
const MAX_TAGS = 20;
/** 单个标签最大长度。 */
const MAX_TAG_LENGTH = 30;
/** base64 dataURL:data:image/<type>;base64,<data>(data 可含 +/ 与 = 填充)。 */
const DATA_URL_RE = /^data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+$/;
/** http(s) 绝对 URL(图片外链)。 */
const HTTP_URL_RE = /^https?:\/\/[^\s]+$/i;
/** Resolve the database instance: injected DB for tests, else global singleton. */
function resolveDb(injected?: Database.Database): Database.Database {
return injected ?? getDb();
}
/**
* 校验图片字段:必须是 base64 dataURL 或 http(s) URL。
*/
function isValidImageData(value: string): boolean {
return DATA_URL_RE.test(value) || HTTP_URL_RE.test(value);
}
/**
* 创建 Showcase 路由。接受可选注入数据库以便测试。
*/
export function createShowcaseRouter(injectedDb?: Database.Database): Router {
const router = Router();
router.post("/works", (req: Request, res: Response): void => {
try {
const body = (req.body ?? {}) as Record<string, unknown>;
// ---- title:非空字符串,长度限制 ----
const title = typeof body.title === "string" ? body.title.trim() : "";
if (!title) {
res.status(400).json({ error: "请输入作品标题" });
return;
}
if (title.length > MAX_TITLE_LENGTH) {
res.status(400).json({ error: "作品标题过长" });
return;
}
// ---- imageData:base64 dataURL 或 http(s) URL ----
const imageData = typeof body.imageData === "string" ? body.imageData : "";
if (!imageData || !isValidImageData(imageData)) {
res.status(400).json({ error: "图片格式无效" });
return;
}
// ---- tags:必须是数组,元素过滤为合法字符串 ----
const rawTags = body.tags;
if (rawTags !== undefined && !Array.isArray(rawTags)) {
res.status(400).json({ error: "标签格式无效" });
return;
}
const tags: string[] = Array.isArray(rawTags)
? rawTags
.filter((t): t is string => typeof t === "string")
.map((t) => t.trim())
.filter((t) => t.length > 0)
.slice(0, MAX_TAGS)
: [];
if (tags.some((t) => t.length > MAX_TAG_LENGTH)) {
res.status(400).json({ error: "标签过长" });
return;
}
// ---- source:可选字符串,默认 manual ----
const source =
typeof body.source === "string" && body.source.trim() !== ""
? body.source.trim().slice(0, 50)
: "manual";
const id = insertWork(resolveDb(injectedDb), { title, imageData, tags, source });
res.status(201).json({ id });
} catch (err) {
console.error("POST /api/showcase/works error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
});
/**
* GET /api/showcase/works — 展示页列表(分页 + 标签筛选 + 来源筛选)。
* 按 created_at DESC, id DESC 排序,返回契约字段 items/total/page/limit。
*/
router.get("/works", (req: Request, res: Response): void => {
const page = parsePositiveInt(req.query["page"], DEFAULT_PAGE);
const limitRaw = parsePositiveInt(req.query["limit"], DEFAULT_LIMIT);
if (page === null || limitRaw === null) {
res.status(400).json({ error: "分页参数无效" });
return;
}
const limit = Math.min(limitRaw, MAX_LIMIT);
const tag = parseQueryString(req.query["tag"]);
const source = parseQueryString(req.query["source"]);
const db = resolveDb(injectedDb);
const { where, params } = buildFilter(tag, source);
const totalRow = db
.prepare(`SELECT COUNT(*) AS total FROM showcase_works w ${where}`)
.get(...params) as { total: number };
const offset = (page - 1) * limit;
const rows = db
.prepare(
`SELECT w.id, w.title, w.image_data, w.tags, w.source, w.created_at
FROM showcase_works w
${where}
ORDER BY w.created_at DESC, w.id DESC
LIMIT ? OFFSET ?`,
)
.all(...params, limit, offset) as ShowcaseWorkRow[];
const items = rows.map(toShowcaseWork);
res.status(200).json({ items, total: totalRow.total, page, limit });
});
/**
* GET /api/showcase/meta — 展示页 SEO 元数据(多语言)。
* 供前端注入 og:title / og:description / og:image,并附带 JSON-LD
* CollectionPage 结构化数据(可整段写入 <script type="application/ld+json">)。
*/
router.get("/meta", (req: Request, res: Response): void => {
const lang = normalizeLang(req.query["lang"]);
const meta = SHOWCASE_META[lang];
res.status(200).json({
title: meta.title,
description: meta.description,
ogImage: resolveOgImage(),
jsonLd: {
"@context": "https://schema.org",
"@type": "CollectionPage",
name: meta.title,
description: meta.description,
inLanguage: lang === "zh" ? "zh-CN" : "en",
},
});
});
return router;
}
/** 分页默认值 / 上限。 */
const DEFAULT_PAGE = 1;
const DEFAULT_LIMIT = 12;
const MAX_LIMIT = 100;
/** 解析正整数查询参数;缺失回退默认值,非法(非整数 / <1)返回 null。 */
function parsePositiveInt(raw: unknown, fallback: number): number | null {
if (raw === undefined) return fallback;
if (typeof raw !== "string" || raw.trim() === "") return fallback;
const n = Number(raw);
if (!Number.isInteger(n) || n < 1) return null;
return n;
}
/** 解析可选查询字符串参数;空值 / 非字符串返回 null。 */
function parseQueryString(raw: unknown): string | null {
if (typeof raw !== "string") return null;
const trimmed = raw.trim();
return trimmed === "" ? null : trimmed;
}
/** 构建标签 / 来源筛选的 WHERE 子句与参数(标签用 json_each 精确匹配)。 */
function buildFilter(tag: string | null, source: string | null): {
where: string;
params: unknown[];
} {
const clauses: string[] = [];
const params: unknown[] = [];
if (tag !== null) {
clauses.push("EXISTS (SELECT 1 FROM json_each(w.tags) je WHERE je.value = ?)");
params.push(tag);
}
if (source !== null) {
clauses.push("w.source = ?");
params.push(source);
}
return {
where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "",
params,
};
}
/** 解析 tags JSON 文本为字符串数组;非法 JSON / 非数组回退空数组。 */
function toShowcaseWork(row: ShowcaseWorkRow): {
id: number;
title: string;
imageUrl: string;
tags: string[];
source: string;
createdAt: string;
} {
let tags: string[] = [];
try {
const parsed: unknown = JSON.parse(row.tags);
if (Array.isArray(parsed)) {
tags = parsed.filter((t): t is string => typeof t === "string");
}
} catch {
// 脏数据回退为空数组
}
return {
id: row.id,
title: row.title,
imageUrl: row.image_data,
tags,
source: row.source,
createdAt: row.created_at,
};
}
/** 规范化 lang 参数:zh/zh-CN/zh-TW → zh;en/en-US/en-GB → en;其余 → zh。 */
export function normalizeLang(raw: unknown): "zh" | "en" {
if (typeof raw !== "string") return "zh";
const lower = raw.trim().toLowerCase();
if (lower === "en" || lower === "en-us" || lower === "en-gb") return "en";
return "zh";
}
/** 展示页 SEO 文案(zh / en)。 */
export const SHOWCASE_META: Readonly<Record<"zh" | "en", { title: string; description: string }>> = {
zh: {
title: "拼豆艺术作品展示 | PERLER LAB 拼豆图纸生成器",
description: "探索来自全球创作者的拼豆艺术作品,下载图纸,即刻开始制作。",
},
en: {
title: "Bead Art Showcase | PERLER LAB Bead Pattern Generator",
description:
"Explore bead art from creators around the world. Download patterns and start making today.",
},
};
/** og:image 默认路径;可用环境变量 SHOWCASE_OG_IMAGE 覆盖为完整 URL。 */
function resolveOgImage(): string {
const custom = process.env["SHOWCASE_OG_IMAGE"];
return custom !== undefined && custom.trim() !== "" ? custom.trim() : "/og-showcase.png";
}
+42
View File
@@ -0,0 +1,42 @@
/**
* chibi Showcase 作品数据层:showcase_works 表的插入操作。
*
* 作品信息:
* - title: 作品标题(非空)
* - imageData: 图片,base64 dataURL 或 http(s) URL
* - tags: 标签数组(入库前 JSON 序列化为 TEXT)
* - source: 作品来源(如 chibi / manual)
*/
import type Database from "better-sqlite3";
/** showcase_works 表行结构。 */
export interface ShowcaseWorkRow {
id: number;
title: string;
image_data: string;
tags: string;
source: string;
created_at: string;
}
/** 发布作品的入参(已通过路由层校验)。 */
export interface InsertWorkInput {
title: string;
imageData: string;
tags: string[];
source: string;
}
/**
* 插入一条作品记录,返回自增主键 id。
*/
export function insertWork(db: Database.Database, input: InsertWorkInput): number {
const info = db
.prepare(
`INSERT INTO showcase_works (title, image_data, tags, source)
VALUES (?, ?, ?, ?)`,
)
.run(input.title, input.imageData, JSON.stringify(input.tags), input.source);
return Number(info.lastInsertRowid);
}
@@ -0,0 +1,104 @@
import { describe, it, expect } from "vitest";
import request from "supertest";
import { createApp } from "../server.js";
import { createTestDatabase } from "../db/index.js";
import { buildJsonLd } from "../color-chart/routes.js";
/** 期望的色号数量(对应 competitor-analysis/palettes 各文件)。 */
const EXPECTED_COUNTS: ReadonlyMap<string, number> = new Map([
["mard", 291],
["artkal-c", 174],
["perler", 103],
["hama", 92],
["pyssla", 18],
["nabbi", 30],
]);
/** JSON-LD 响应体类型。 */
interface JsonLdList {
"@context": string;
"@type": string;
name: string;
url: string;
mainEntity: {
"@type": string;
numberOfItems: number;
itemListElement: {
"@type": string;
position: number;
item: { "@type": string; name: string; identifier: string; color: string };
}[];
};
}
describe("GET /api/color-chart/:brand(JSON-LD 结构化数据)", () => {
const app = createApp(createTestDatabase());
it("6 个品牌均可访问且返回 CollectionPage + ItemList schema", async () => {
for (const [brand, count] of EXPECTED_COUNTS) {
const res = await request(app).get(`/api/color-chart/${brand}`);
expect(res.status, `${brand} 应返回 200`).toBe(200);
expect(res.headers["content-type"]).toContain("application/ld+json");
const body = res.body as JsonLdList;
expect(body["@context"]).toBe("https://schema.org");
expect(body["@type"]).toBe("CollectionPage");
expect(body.url).toBe(`/color-chart/${brand}`);
expect(body.mainEntity["@type"]).toBe("ItemList");
expect(body.mainEntity.numberOfItems).toBe(count);
expect(body.mainEntity.itemListElement).toHaveLength(count);
}
});
it("每个品牌 itemListElement 的 position 连续且 item 字段合法", async () => {
for (const brand of EXPECTED_COUNTS.keys()) {
const res = await request(app).get(`/api/color-chart/${brand}`);
const body = res.body as JsonLdList;
body.mainEntity.itemListElement.forEach((element, index) => {
expect(element["@type"]).toBe("ListItem");
expect(element.position).toBe(index + 1);
expect(typeof element.item.name).toBe("string");
expect(element.item.name.length).toBeGreaterThan(0);
expect(typeof element.item.identifier).toBe("string");
expect(element.item.color).toMatch(/^#[0-9A-F]{6}$/i);
});
}
});
it("mard 返回 291 个不重复色号(A01… 格式)", async () => {
const res = await request(app).get("/api/color-chart/mard");
const body = res.body as JsonLdList;
const ids = body.mainEntity.itemListElement.map((e) => e.item.identifier);
expect(ids).toHaveLength(291);
expect(new Set(ids).size).toBe(291);
expect(ids[0]).toBe("A01");
});
it("artkal-c / perler / hama / pyssla / nabbi 色号数量与参考数据一致", async () => {
const brandFileCounts: ReadonlyMap<string, number> = new Map([
["artkal-c", 174],
["perler", 103],
["hama", 92],
["pyssla", 18],
["nabbi", 30],
]);
for (const [brand, count] of brandFileCounts) {
const res = await request(app).get(`/api/color-chart/${brand}`);
const body = res.body as JsonLdList;
expect(body.mainEntity.itemListElement).toHaveLength(count);
}
});
it("buildJsonLd 空色号表返回 numberOfItems=0 与空列表", () => {
const ld = buildJsonLd({ id: "empty", name: "Empty", colors: [] });
const main = ld["mainEntity"] as { numberOfItems: number; itemListElement: unknown[] };
expect(main.numberOfItems).toBe(0);
expect(main.itemListElement).toHaveLength(0);
});
it("未知品牌返回 404 中文错误", async () => {
const res = await request(app).get("/api/color-chart/UNKNOWN");
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: "品牌不存在" });
});
});
@@ -0,0 +1,444 @@
import { describe, it, expect } from "vitest";
import request from "supertest";
import type Database from "better-sqlite3";
import { createApp } from "../server.js";
import { createTestDatabase } from "../db/index.js";
import { insertWork } from "../showcase/service.js";
/** 合法的 base64 dataURL 图片。 */
const VALID_DATA_URL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
/** 合法的 http(s) URL 图片。 */
const VALID_URL = "https://example.com/works/cat.png";
/** 合法请求体,overrides 可覆盖任意字段。 */
function baseBody(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
title: "我的小猫咪",
imageData: VALID_DATA_URL,
tags: ["宠物", "猫"],
source: "chibi",
...overrides,
};
}
describe("insertWork(showcase_works 数据层)", () => {
it("插入作品并返回自增 id,tags 序列化为 JSON 文本", () => {
const db = createTestDatabase();
const id = insertWork(db, {
title: "小狗",
imageData: VALID_URL,
tags: ["宠物", "狗"],
source: "manual",
});
expect(id).toBeGreaterThan(0);
const row = db.prepare("SELECT * FROM showcase_works WHERE id = ?").get(id) as {
title: string;
image_data: string;
tags: string;
source: string;
};
expect(row.title).toBe("小狗");
expect(row.image_data).toBe(VALID_URL);
expect(row.tags).toBe('["宠物","狗"]');
expect(row.source).toBe("manual");
});
it("连续插入两条 id 递增", () => {
const db = createTestDatabase();
const a = insertWork(db, { title: "A", imageData: VALID_URL, tags: [], source: "manual" });
const b = insertWork(db, { title: "B", imageData: VALID_URL, tags: [], source: "manual" });
expect(b).toBe(a + 1);
});
});
describe("POST /api/showcase/works 路由", () => {
it("201 返回 { id },dataURL 图片入库成功", async () => {
const db = createTestDatabase();
const app = createApp(db);
const res = await request(app).post("/api/showcase/works").send(baseBody());
expect(res.status).toBe(201);
expect(typeof res.body.id).toBe("number");
expect(res.body.id).toBeGreaterThan(0);
const row = db.prepare("SELECT * FROM showcase_works WHERE id = ?").get(res.body.id) as {
title: string;
source: string;
};
expect(row.title).toBe("我的小猫咪");
expect(row.source).toBe("chibi");
});
it("支持 http(s) URL 图片", async () => {
const app = createApp(createTestDatabase());
const res = await request(app)
.post("/api/showcase/works")
.send(baseBody({ imageData: VALID_URL }));
expect(res.status).toBe(201);
expect(typeof res.body.id).toBe("number");
});
it("title 为空返回 400 请输入作品标题", async () => {
const app = createApp(createTestDatabase());
const res = await request(app).post("/api/showcase/works").send(baseBody({ title: " " }));
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "请输入作品标题" });
});
it("缺少 title 返回 400 请输入作品标题", async () => {
const app = createApp(createTestDatabase());
const { title: _removed, ...rest } = baseBody();
void _removed;
const res = await request(app).post("/api/showcase/works").send(rest);
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "请输入作品标题" });
});
it("title 超过 100 字符返回 400 作品标题过长", async () => {
const app = createApp(createTestDatabase());
const res = await request(app)
.post("/api/showcase/works")
.send(baseBody({ title: "长".repeat(101) }));
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "作品标题过长" });
});
it("imageData 非 base64/URL 返回 400 图片格式无效", async () => {
const app = createApp(createTestDatabase());
const res = await request(app)
.post("/api/showcase/works")
.send(baseBody({ imageData: "not-an-image" }));
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "图片格式无效" });
});
it("缺少 imageData 返回 400 图片格式无效", async () => {
const app = createApp(createTestDatabase());
const { imageData: _removed, ...rest } = baseBody();
void _removed;
const res = await request(app).post("/api/showcase/works").send(rest);
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "图片格式无效" });
});
it("tags 不是数组返回 400 标签格式无效", async () => {
const app = createApp(createTestDatabase());
const res = await request(app)
.post("/api/showcase/works")
.send(baseBody({ tags: "宠物" }));
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "标签格式无效" });
});
it("tags 缺省时默认空数组并入库", async () => {
const db = createTestDatabase();
const app = createApp(db);
const res = await request(app).post("/api/showcase/works").send(baseBody({ tags: undefined }));
expect(res.status).toBe(201);
const row = db.prepare("SELECT tags FROM showcase_works WHERE id = ?").get(res.body.id) as {
tags: string;
};
expect(row.tags).toBe("[]");
});
it("tags 过滤非字符串元素并截断到 20 个", async () => {
const db = createTestDatabase();
const app = createApp(db);
const many = Array.from({ length: 30 }, (_, i) => `tag-${i}`);
const res = await request(app)
.post("/api/showcase/works")
.send(baseBody({ tags: [...many, 123, null, undefined] }));
expect(res.status).toBe(201);
const row = db.prepare("SELECT tags FROM showcase_works WHERE id = ?").get(res.body.id) as {
tags: string;
};
const stored = JSON.parse(row.tags) as string[];
expect(stored).toHaveLength(20);
expect(stored.every((t) => typeof t === "string")).toBe(true);
});
it("单个标签超过 30 字符返回 400 标签过长", async () => {
const app = createApp(createTestDatabase());
const res = await request(app)
.post("/api/showcase/works")
.send(baseBody({ tags: ["x".repeat(31)] }));
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "标签过长" });
});
it("source 缺省时默认 manual", async () => {
const db = createTestDatabase();
const app = createApp(db);
const res = await request(app).post("/api/showcase/works").send(baseBody({ source: undefined }));
expect(res.status).toBe(201);
const row = db.prepare("SELECT source FROM showcase_works WHERE id = ?").get(res.body.id) as {
source: string;
};
expect(row.source).toBe("manual");
});
});
describe("GET /api/showcase/works 列表(T-100:分页 + 标签筛选)", () => {
/** 造一批作品:tags 与 created_at 可控,便于断言排序与筛选。 */
function seedWorks(db: Database.Database): void {
const insert = db.prepare(
`INSERT INTO showcase_works (title, image_data, tags, source, created_at)
VALUES (?, ?, ?, ?, ?)`,
);
const works: Array<[string, string, string[], string, string]> = [
["落日余晖", VALID_URL, ["卡通动漫", "精选"], "chibi", "2026-08-01 10:00:00"],
["原神启动", VALID_URL, ["游戏像素", "精选"], "chibi", "2026-08-02 10:00:00"],
["炉石相框", VALID_URL, ["游戏像素"], "chibi", "2026-08-03 10:00:00"],
["蠢蠢的同学", VALID_URL, ["动物萌宠"], "chibi", "2026-08-04 10:00:00"],
["哈夫币", VALID_URL, ["游戏像素", "进阶挑战"], "manual", "2026-08-05 10:00:00"],
["自用狗拼豆", VALID_URL, ["动物萌宠"], "chibi", "2026-08-06 10:00:00"],
["天星", VALID_URL, ["新手入门"], "chibi", "2026-08-07 10:00:00"],
["伯库林", VALID_URL, ["节日限定"], "chibi", "2026-08-08 10:00:00"],
];
for (const [title, image, tags, source, createdAt] of works) {
insert.run(title, image, JSON.stringify(tags), source, createdAt);
}
}
it("返回 items/total/page/limit 契约字段,默认按 created_at DESC 排序", async () => {
const db = createTestDatabase();
seedWorks(db);
const app = createApp(db);
const res = await request(app).get("/api/showcase/works");
expect(res.status).toBe(200);
const body = res.body as {
items: Array<{
id: number;
title: string;
imageUrl: string;
tags: string[];
source: string;
createdAt: string;
}>;
total: number;
page: number;
limit: number;
};
expect(body.total).toBe(8);
expect(body.page).toBe(1);
expect(body.limit).toBe(12);
expect(body.items).toHaveLength(8);
expect(body.items.map((w) => w.title)).toEqual([
"伯库林",
"天星",
"自用狗拼豆",
"哈夫币",
"蠢蠢的同学",
"炉石相框",
"原神启动",
"落日余晖",
]);
// 字段映射契约:image_data → imageUrl,tags 解析为数组
const first = body.items[0]!;
expect(first.imageUrl).toBe(VALID_URL);
expect(first.tags).toEqual(["节日限定"]);
expect(typeof first.createdAt).toBe("string");
expect(typeof first.id).toBe("number");
expect(first.source).toBe("chibi");
});
it("分页:page=2&limit=3 返回第 2 页,total 为全部记录数", async () => {
const db = createTestDatabase();
seedWorks(db);
const app = createApp(db);
const res = await request(app).get("/api/showcase/works?page=2&limit=3");
expect(res.status).toBe(200);
const body = res.body as {
items: Array<{ title: string }>;
total: number;
page: number;
limit: number;
};
expect(body.total).toBe(8);
expect(body.page).toBe(2);
expect(body.limit).toBe(3);
expect(body.items).toHaveLength(3);
// 倒序第 4..6 条:哈夫币(5), 蠢蠢的同学(4), 炉石相框(3)
expect(body.items.map((w) => w.title)).toEqual(["哈夫币", "蠢蠢的同学", "炉石相框"]);
});
it("超出范围的页返回空 items 但保留 total", async () => {
const db = createTestDatabase();
seedWorks(db);
const app = createApp(db);
const res = await request(app).get("/api/showcase/works?page=99&limit=12");
expect(res.status).toBe(200);
expect(res.body.items).toEqual([]);
expect(res.body.total).toBe(8);
expect(res.body.page).toBe(99);
});
it("标签筛选:tag=游戏像素 只返回带该标签的作品", async () => {
const db = createTestDatabase();
seedWorks(db);
const app = createApp(db);
const res = await request(app).get("/api/showcase/works?tag=游戏像素");
expect(res.status).toBe(200);
const body = res.body as { items: Array<{ title: string; tags: string[] }>; total: number };
expect(body.total).toBe(3);
expect(body.items.map((w) => w.title)).toEqual(["哈夫币", "炉石相框", "原神启动"]);
for (const item of body.items) {
expect(item.tags).toContain("游戏像素");
}
});
it("标签筛选 + 分页组合:tag=游戏像素&limit=2&page=2", async () => {
const db = createTestDatabase();
seedWorks(db);
const app = createApp(db);
const res = await request(app).get("/api/showcase/works?tag=游戏像素&limit=2&page=2");
expect(res.status).toBe(200);
const body = res.body as { items: Array<{ title: string }>; total: number; page: number };
expect(body.total).toBe(3);
expect(body.page).toBe(2);
// 筛选后倒序:哈夫币(5), 炉石相框(3), 原神启动(2);第 2 页取最后一页 1 条
expect(body.items.map((w) => w.title)).toEqual(["原神启动"]);
});
it("来源筛选:source=chibi 只返回 chibi 作品", async () => {
const db = createTestDatabase();
seedWorks(db);
const app = createApp(db);
const res = await request(app).get("/api/showcase/works?source=chibi");
expect(res.status).toBe(200);
const body = res.body as { items: Array<{ source: string }>; total: number };
expect(body.total).toBe(7);
expect(body.items.every((w) => w.source === "chibi")).toBe(true);
});
it("标签 + 来源组合筛选:tag=游戏像素&source=chibi", async () => {
const db = createTestDatabase();
seedWorks(db);
const app = createApp(db);
const res = await request(app).get("/api/showcase/works?tag=游戏像素&source=chibi");
expect(res.status).toBe(200);
const body = res.body as { items: Array<{ title: string }>; total: number };
// 游戏像素中仅原神启动 / 炉石相框为 chibi(哈夫币是 manual)
expect(body.total).toBe(2);
expect(body.items.map((w) => w.title)).toEqual(["炉石相框", "原神启动"]);
});
it("无匹配标签返回空列表 total=0", async () => {
const db = createTestDatabase();
seedWorks(db);
const app = createApp(db);
const res = await request(app).get("/api/showcase/works?tag=不存在的标签");
expect(res.status).toBe(200);
expect(res.body.items).toEqual([]);
expect(res.body.total).toBe(0);
});
it("空库返回空列表 total=0", async () => {
const app = createApp(createTestDatabase());
const res = await request(app).get("/api/showcase/works");
expect(res.status).toBe(200);
expect(res.body).toEqual({ items: [], total: 0, page: 1, limit: 12 });
});
it("limit 超过上限 100 时被截断为 100", async () => {
const db = createTestDatabase();
seedWorks(db);
const app = createApp(db);
const res = await request(app).get("/api/showcase/works?limit=999");
expect(res.status).toBe(200);
expect(res.body.limit).toBe(100);
});
it("page/limit 非正整数返回 400 分页参数无效", async () => {
const app = createApp(createTestDatabase());
const bad = ["page=0", "page=abc", "limit=-1", "limit=1.5", "page=1.2"];
for (const q of bad) {
const res = await request(app).get(`/api/showcase/works?${q}`);
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "分页参数无效" });
}
});
});
describe("GET /api/showcase/meta 展示页 SEO 元数据(T-101)", () => {
it("缺省 lang 返回中文 title/description/ogImage 与 JSON-LD", async () => {
const app = createApp(createTestDatabase());
const res = await request(app).get("/api/showcase/meta");
expect(res.status).toBe(200);
const body = res.body as {
title: string;
description: string;
ogImage: string;
jsonLd: { "@context": string; "@type": string; inLanguage: string };
};
expect(body.title).toContain("拼豆艺术作品展示");
expect(body.description.length).toBeGreaterThan(0);
expect(body.ogImage).toBe("/og-showcase.png");
expect(body.jsonLd["@context"]).toBe("https://schema.org");
expect(body.jsonLd["@type"]).toBe("CollectionPage");
expect(body.jsonLd.inLanguage).toBe("zh-CN");
});
it("lang=zh 与 lang=zh-CN 返回中文文案", async () => {
const app = createApp(createTestDatabase());
for (const lang of ["zh", "zh-CN", "zh-TW"]) {
const res = await request(app).get(`/api/showcase/meta?lang=${lang}`);
expect(res.status).toBe(200);
expect((res.body as { title: string }).title).toContain("拼豆艺术作品展示");
expect((res.body as { jsonLd: { inLanguage: string } }).jsonLd.inLanguage).toBe("zh-CN");
}
});
it("lang=en 返回英文文案,inLanguage=en", async () => {
const app = createApp(createTestDatabase());
const res = await request(app).get("/api/showcase/meta?lang=en");
expect(res.status).toBe(200);
const body = res.body as {
title: string;
description: string;
jsonLd: { inLanguage: string };
};
expect(body.title).toContain("Bead Art Showcase");
expect(body.description.length).toBeGreaterThan(0);
expect(body.jsonLd.inLanguage).toBe("en");
});
it("未知 lang 回退中文", async () => {
const app = createApp(createTestDatabase());
const res = await request(app).get("/api/showcase/meta?lang=fr");
expect(res.status).toBe(200);
expect((res.body as { title: string }).title).toContain("拼豆艺术作品展示");
});
});