feat: V1.2 P0 批次入库——四页合规/作品详情页/后端详情接口

This commit is contained in:
Sisyphus committed 2026-08-15 15:13:51 +08:00
1 parent f53f0a2b25
commit 346f41d391
23 files changed
+3495 -173

No files matched your search

+25
View File
@@ -51,6 +51,31 @@ export function initDatabase(config?: DbConfig): Database.Database {
*/
function runMigrations(db: Database.Database): void {
db.exec(SCHEMA_SQL);
migrateShowcaseSpec(db);
}
/**
* 为 T-099~T-102 期间创建的旧 showcase_works 表补齐规格列。
* 新库由 SCHEMA_SQL 一次性建全列;旧库逐列 ALTER TABLE ADD COLUMN(幂等)。
*/
function migrateShowcaseSpec(db: Database.Database): void {
const columns = new Set(
(db.prepare("PRAGMA table_info(showcase_works)").all() as Array<{ name: string }>).map(
(col) => col.name,
),
);
if (columns.size === 0) return; // 表不存在:新库将由 SCHEMA_SQL 建全列
const additions: ReadonlyArray<[name: string, declaration: string]> = [
["width", "INTEGER"],
["height", "INTEGER"],
["brand", "TEXT"],
["materials", "TEXT"],
];
for (const [name, declaration] of additions) {
if (!columns.has(name)) {
db.exec(`ALTER TABLE showcase_works ADD COLUMN ${name} ${declaration}`);
}
}
}
/**
+7 -1
View File
@@ -110,13 +110,19 @@ 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)
-- 规格列(T-131 详情页需要):width/height 图纸宽高(格);brand 材料品牌(如 MARD);
-- materials 用料清单 JSON 文本(如 '[{"code":"A7","count":980}]',name 可选),缺省为 NULL
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'))
created_at TEXT NOT NULL DEFAULT (datetime('now')),
width INTEGER,
height INTEGER,
brand TEXT,
materials TEXT
);
-- 索引:按创建时间倒序查询作品列表(Showcase 展示页主路径)
+201 -3
View File
@@ -2,12 +2,16 @@
* chibi Showcase 作品 API。
*
* POST /api/showcase/works(T-099 发布接口)
* Request: { title: string, imageData: string, tags?: string[], source?: string }
* Request: { title: string, imageData: string, tags?: string[], source?: string,
* width?: number, height?: number, brand?: string, materials?: MaterialLine[] }
* Response: 201 { id: number }
* 400 { error: "请输入作品标题" } 标题为空
* 400 { error: "作品标题过长" } 标题超过 100 字符
* 400 { error: "图片格式无效" } imageData 非 base64 dataURL 也非 http(s) URL
* 400 { error: "标签格式无效" } tags 不是数组
* 400 { error: "尺寸参数无效" } width/height 非 1..512 整数
* 400 { error: "品牌格式无效" } brand 非字符串/超长
* 400 { error: "用料清单格式无效" } materials 非法
* 500 服务器内部错误
*
* GET /api/showcase/works(T-100 展示页列表)
@@ -16,6 +20,12 @@
* total, page, limit }(items 按 created_at DESC, id DESC)
* 400 { error: "分页参数无效" } page/limit 非正整数
*
* GET /api/showcase/works/:id(T-131 作品详情)
* Response: 200 { id, title, imageUrl, tags, source, createdAt,
* spec: { width, height, brand, materials } }
* 400 { error: "作品 ID 无效" } id 非正整数
* 404 { error: "作品不存在" } id 无对应记录
*
* GET /api/showcase/meta(T-101 展示页 SEO 元数据)
* Query: lang=zh|en(缺省 zh)
* Response: 200 { title, description, ogImage, jsonLd }
@@ -25,7 +35,12 @@ 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";
import {
insertWork,
getWorkById,
type ShowcaseWorkRow,
type MaterialLine,
} from "./service.js";
/** 标题最大长度。 */
const MAX_TITLE_LENGTH = 100;
@@ -36,6 +51,21 @@ const MAX_TAGS = 20;
/** 单个标签最大长度。 */
const MAX_TAG_LENGTH = 30;
/** 图纸单边最大格数(与服务端导出能力 512×512 对齐)。 */
const MAX_GRID_SIZE = 512;
/** 用料清单最大条目数(与前端分享码 256 色上限对齐)。 */
const MAX_MATERIALS = 256;
/** 品牌名最大长度。 */
const MAX_BRAND_LENGTH = 50;
/** 用料清单单行色号最大长度。 */
const MAX_MATERIAL_CODE_LENGTH = 20;
/** 用料清单单行名称最大长度。 */
const MAX_MATERIAL_NAME_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+/=]+$/;
@@ -106,7 +136,38 @@ export function createShowcaseRouter(injectedDb?: Database.Database): Router {
? body.source.trim().slice(0, 50)
: "manual";
const id = insertWork(resolveDb(injectedDb), { title, imageData, tags, source });
// ---- 规格字段(T-131:详情页需要的尺寸/品牌/用料信息,均可选)----
const width = validateOptionalGridSize(body.width);
if (width.error !== null) {
res.status(400).json({ error: width.error });
return;
}
const height = validateOptionalGridSize(body.height);
if (height.error !== null) {
res.status(400).json({ error: height.error });
return;
}
const brand = validateBrand(body.brand);
if (brand.error !== null) {
res.status(400).json({ error: brand.error });
return;
}
const materials = validateMaterials(body.materials);
if (materials.error !== null) {
res.status(400).json({ error: materials.error });
return;
}
const id = insertWork(resolveDb(injectedDb), {
title,
imageData,
tags,
source,
width: width.value,
height: height.value,
brand: brand.value,
materials: materials.value,
});
res.status(201).json({ id });
} catch (err) {
console.error("POST /api/showcase/works error:", err);
@@ -152,6 +213,31 @@ export function createShowcaseRouter(injectedDb?: Database.Database): Router {
res.status(200).json({ items, total: totalRow.total, page, limit });
});
/**
* GET /api/showcase/works/:id — 作品详情(T-131)。
* 按 id 查询单作品:返回基础字段 + spec 规格块(尺寸/品牌/用料清单,缺省可空)。
* id 非正整数 → 400;记录不存在 → 404。
*/
router.get("/works/:id", (req: Request, res: Response): void => {
try {
const id = parsePositiveId(req.params["id"]);
if (id === null) {
res.status(400).json({ error: "作品 ID 无效" });
return;
}
const db = resolveDb(injectedDb);
const row = getWorkById(db, id);
if (row === undefined) {
res.status(404).json({ error: "作品不存在" });
return;
}
res.status(200).json(toWorkDetail(row));
} catch (err) {
console.error("GET /api/showcase/works/:id error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
});
/**
* GET /api/showcase/meta — 展示页 SEO 元数据(多语言)。
* 供前端注入 og:title / og:description / og:image,并附带 JSON-LD
@@ -248,6 +334,118 @@ function toShowcaseWork(row: ShowcaseWorkRow): {
};
}
/** 解析路径参数 :id 为合法正整数(AUTOINCREMENT id ≥ 1);非法返回 null。 */
function parsePositiveId(raw: unknown): number | null {
if (typeof raw !== "string" || raw.trim() === "") return null;
if (!/^[1-9]\d*$/.test(raw.trim())) return null;
const n = Number(raw.trim());
if (!Number.isSafeInteger(n) || n < 1) return null;
return n;
}
/** 校验可选规格整数(1..MAX_GRID_SIZE);缺省/空返回 null,非法返回错误信息。 */
function validateOptionalGridSize(raw: unknown): { value: number | null; error: string | null } {
if (raw === undefined || raw === null) return { value: null, error: null };
if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1 || raw > MAX_GRID_SIZE) {
return { value: null, error: "尺寸参数无效" };
}
return { value: raw, error: null };
}
/** 校验可选品牌名(非空字符串,≤50 字符);非法返回错误信息。 */
function validateBrand(raw: unknown): { value: string | null; error: string | null } {
if (raw === undefined || raw === null) return { value: null, error: null };
if (typeof raw !== "string") return { value: null, error: "品牌格式无效" };
const trimmed = raw.trim();
if (trimmed === "" || trimmed.length > MAX_BRAND_LENGTH) {
return { value: null, error: "品牌格式无效" };
}
return { value: trimmed, error: null };
}
/** 校验可选用料清单({code, count, name?}[],≤256 行);非法返回错误信息。 */
function validateMaterials(raw: unknown): { value: MaterialLine[] | null; error: string | null } {
if (raw === undefined || raw === null) return { value: null, error: null };
if (!Array.isArray(raw) || raw.length > MAX_MATERIALS) {
return { value: null, error: "用料清单格式无效" };
}
const lines: MaterialLine[] = [];
for (const item of raw) {
if (typeof item !== "object" || item === null) {
return { value: null, error: "用料清单格式无效" };
}
const rec = item as Record<string, unknown>;
if (
typeof rec.code !== "string" ||
rec.code.trim() === "" ||
rec.code.length > MAX_MATERIAL_CODE_LENGTH
) {
return { value: null, error: "用料清单格式无效" };
}
if (typeof rec.count !== "number" || !Number.isInteger(rec.count) || rec.count < 1) {
return { value: null, error: "用料清单格式无效" };
}
const line: MaterialLine = { code: rec.code.trim(), count: rec.count };
if (rec.name !== undefined) {
if (
typeof rec.name !== "string" ||
rec.name.trim() === "" ||
rec.name.length > MAX_MATERIAL_NAME_LENGTH
) {
return { value: null, error: "用料清单格式无效" };
}
line.name = rec.name.trim();
}
lines.push(line);
}
return { value: lines, error: null };
}
/** 解析 materials JSON 文本为用料清单;缺省/脏数据返回 null。 */
function parseMaterials(raw: string | null): MaterialLine[] | null {
if (raw === null || raw === "") return null;
try {
const parsed: unknown = JSON.parse(raw);
if (!Array.isArray(parsed)) return null;
return parsed.filter(
(l): l is MaterialLine =>
typeof l === "object" &&
l !== null &&
typeof (l as MaterialLine).code === "string" &&
typeof (l as MaterialLine).count === "number",
);
} catch {
return null;
}
}
/** 详情接口响应结构:基础字段 + spec 规格块(尺寸/品牌/用料,缺省可空)。 */
function toWorkDetail(row: ShowcaseWorkRow): {
id: number;
title: string;
imageUrl: string;
tags: string[];
source: string;
createdAt: string;
spec: {
width: number | null;
height: number | null;
brand: string | null;
materials: MaterialLine[] | null;
};
} {
const base = toShowcaseWork(row);
return {
...base,
spec: {
width: row.width,
height: row.height,
brand: row.brand,
materials: parseMaterials(row.materials),
},
};
}
/** 规范化 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";
+42 -3
View File
@@ -18,6 +18,17 @@ export interface ShowcaseWorkRow {
tags: string;
source: string;
created_at: string;
width: number | null;
height: number | null;
brand: string | null;
materials: string | null;
}
/** 用料清单单行:MARD 色号 + 数量(name 可选)。 */
export interface MaterialLine {
code: string;
count: number;
name?: string;
}
/** 发布作品的入参(已通过路由层校验)。 */
@@ -26,17 +37,45 @@ export interface InsertWorkInput {
imageData: string;
tags: string[];
source: string;
width?: number | null;
height?: number | null;
brand?: string | null;
materials?: MaterialLine[] | null;
}
/**
* 插入一条作品记录,返回自增主键 id。
* 规格字段可选(T-131):缺省时写入 NULL,详情接口返回可空规格。
*/
export function insertWork(db: Database.Database, input: InsertWorkInput): number {
const info = db
.prepare(
`INSERT INTO showcase_works (title, image_data, tags, source)
VALUES (?, ?, ?, ?)`,
`INSERT INTO showcase_works (title, image_data, tags, source, width, height, brand, materials)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(input.title, input.imageData, JSON.stringify(input.tags), input.source);
.run(
input.title,
input.imageData,
JSON.stringify(input.tags),
input.source,
input.width ?? null,
input.height ?? null,
input.brand ?? null,
input.materials === undefined || input.materials === null
? null
: JSON.stringify(input.materials),
);
return Number(info.lastInsertRowid);
}
/**
* 按 id 查询单条作品记录;不存在返回 undefined(详情接口主查询)。
*/
export function getWorkById(
db: Database.Database,
id: number,
): ShowcaseWorkRow | undefined {
return db.prepare(`SELECT * FROM showcase_works WHERE id = ?`).get(id) as
| ShowcaseWorkRow
| undefined;
}
+192 -2
View File
@@ -1,8 +1,11 @@
import { describe, it, expect } from "vitest";
import request from "supertest";
import type Database from "better-sqlite3";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import Database from "better-sqlite3";
import { createApp } from "../server.js";
import { createTestDatabase } from "../db/index.js";
import { createTestDatabase, initDatabase, closeDatabase } from "../db/index.js";
import { insertWork } from "../showcase/service.js";
/** 合法的 base64 dataURL 图片。 */
@@ -442,3 +445,190 @@ describe("GET /api/showcase/meta 展示页 SEO 元数据(T-101)", () => {
});
});
describe("GET /api/showcase/works/:id 作品详情(T-131)", () => {
/** 详情响应 spec 块的形状。 */
interface SpecShape {
width: number | null;
height: number | null;
brand: string | null;
materials: Array<{ code: string; count: number; name?: string }> | null;
}
it("200 返回详情契约:基础字段 + 缺省可空 spec 规格块", async () => {
const db = createTestDatabase();
const app = createApp(db);
const created = await request(app).post("/api/showcase/works").send(baseBody());
const id = created.body.id as number;
const res = await request(app).get(`/api/showcase/works/${id}`);
expect(res.status).toBe(200);
const body = res.body as {
id: number;
title: string;
imageUrl: string;
tags: string[];
source: string;
createdAt: string;
spec: SpecShape;
};
expect(body.id).toBe(id);
expect(body.title).toBe("我的小猫咪");
expect(body.imageUrl).toBe(VALID_DATA_URL);
expect(body.tags).toEqual(["宠物", "猫"]);
expect(body.source).toBe("chibi");
expect(typeof body.createdAt).toBe("string");
expect(body.spec).toEqual({ width: null, height: null, brand: null, materials: null });
});
it("POST 携带规格字段后,详情原样返回 width/height/brand/materials", async () => {
const db = createTestDatabase();
const app = createApp(db);
const created = await request(app)
.post("/api/showcase/works")
.send(
baseBody({
width: 99,
height: 99,
brand: "MARD",
materials: [
{ code: "A7", name: "橙红", count: 980 },
{ code: "H12", count: 512 },
],
}),
);
const id = created.body.id as number;
const res = await request(app).get(`/api/showcase/works/${id}`);
expect(res.status).toBe(200);
expect((res.body as { spec: SpecShape }).spec).toEqual({
width: 99,
height: 99,
brand: "MARD",
materials: [
{ code: "A7", name: "橙红", count: 980 },
{ code: "H12", count: 512 },
],
});
});
it("列表接口保持 T-100 契约,不泄漏 spec 规格字段", async () => {
const db = createTestDatabase();
const app = createApp(db);
await request(app).post("/api/showcase/works").send(baseBody({ width: 64, height: 64 }));
const res = await request(app).get("/api/showcase/works");
expect(res.status).toBe(200);
const item = (res.body as { items: Array<Record<string, unknown>> }).items[0]!;
expect(item).not.toHaveProperty("spec");
expect(item["width"]).toBeUndefined();
});
it("id 不存在返回 404 作品不存在", async () => {
const app = createApp(createTestDatabase());
const res = await request(app).get("/api/showcase/works/9999");
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: "作品不存在" });
});
it("空库查询任意 id 返回 404", async () => {
const app = createApp(createTestDatabase());
const res = await request(app).get("/api/showcase/works/1");
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: "作品不存在" });
});
it("非法 id 返回 400 作品 ID 无效", async () => {
const app = createApp(createTestDatabase());
const bad = ["abc", "0", "-1", "1.5", "1e3", "12abc", "99999999999999999999"];
for (const id of bad) {
const res = await request(app).get(`/api/showcase/works/${encodeURIComponent(id)}`);
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "作品 ID 无效" });
}
});
it("POST 规格校验:width/height 非法返回 400 尺寸参数无效", async () => {
const app = createApp(createTestDatabase());
for (const width of [0, -1, 513, 1.5, "99"]) {
const res = await request(app).post("/api/showcase/works").send(baseBody({ width }));
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "尺寸参数无效" });
}
const res = await request(app)
.post("/api/showcase/works")
.send(baseBody({ height: -2 }));
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "尺寸参数无效" });
});
it("POST 规格校验:brand / materials 非法返回 400", async () => {
const app = createApp(createTestDatabase());
const badBrand = await request(app)
.post("/api/showcase/works")
.send(baseBody({ brand: 123 }));
expect(badBrand.status).toBe(400);
expect(badBrand.body).toEqual({ error: "品牌格式无效" });
const badMaterials = await request(app)
.post("/api/showcase/works")
.send(baseBody({ materials: "A7" }));
expect(badMaterials.status).toBe(400);
expect(badMaterials.body).toEqual({ error: "用料清单格式无效" });
const emptyCode = await request(app)
.post("/api/showcase/works")
.send(baseBody({ materials: [{ code: "", count: 1 }] }));
expect(emptyCode.status).toBe(400);
expect(emptyCode.body).toEqual({ error: "用料清单格式无效" });
const zeroCount = await request(app)
.post("/api/showcase/works")
.send(baseBody({ materials: [{ code: "A7", count: 0 }] }));
expect(zeroCount.status).toBe(400);
expect(zeroCount.body).toEqual({ error: "用料清单格式无效" });
});
it("迁移:旧结构 showcase_works 表在 initDatabase 时补齐规格列", () => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "perler-migrate-"));
const dbPath = path.join(tmpDir, "old.db");
try {
const old = new Database(dbPath);
old.exec(`
CREATE TABLE 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'))
);
`);
old.close();
const db = initDatabase({ dbPath });
const cols = (db.prepare("PRAGMA table_info(showcase_works)").all() as Array<{
name: string;
}>).map((c) => c.name);
for (const col of ["width", "height", "brand", "materials"]) {
expect(cols).toContain(col);
}
db.prepare(
"INSERT INTO showcase_works (title, image_data, width, height, brand) VALUES (?, ?, ?, ?, ?)",
).run("迁移作品", VALID_URL, 99, 99, "MARD");
const row = db.prepare("SELECT width, height, brand FROM showcase_works").get() as {
width: number;
height: number;
brand: string;
};
expect(row.width).toBe(99);
expect(row.height).toBe(99);
expect(row.brand).toBe("MARD");
} finally {
closeDatabase();
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
});