From b33d5c466d98c50e44351b252918a5f41157a718 Mon Sep 17 00:00:00 2001 From: Sisyphus Date: Sun, 23 Aug 2026 02:17:16 +0800 Subject: [PATCH] =?UTF-8?q?feat(chibi):=20GET=20/api/chibi/history=20?= =?UTF-8?q?=E8=BF=917=E5=A4=A9=E7=94=9F=E6=88=90=E8=AE=B0=E5=BD=95=20+=20i?= =?UTF-8?q?mage=5Fdata=20=E5=B9=82=E7=AD=89=E8=BF=81=E7=A7=BB=20+=204?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- perler-lab-server/src/chibi/generate.ts | 11 +++- perler-lab-server/src/chibi/routes.ts | 64 +++++++++++++++++++++- perler-lab-server/src/db/index.ts | 33 +++++++++++- perler-lab-server/src/db/schema.ts | 2 + perler-lab-server/src/tests/chibi.test.ts | 65 +++++++++++++++++++++++ 5 files changed, 171 insertions(+), 4 deletions(-) diff --git a/perler-lab-server/src/chibi/generate.ts b/perler-lab-server/src/chibi/generate.ts index 8c83ee9..ea81eba 100644 --- a/perler-lab-server/src/chibi/generate.ts +++ b/perler-lab-server/src/chibi/generate.ts @@ -5,7 +5,8 @@ * 组装提示词 -> 调用 OpenAI 兼容图像接口 (AI_IMAGE_API_URL / * AI_IMAGE_API_KEY),未配置接口地址时使用内置 mock 模式生成占位图。 */ -import type { Db } from "../db/index.js"; +import type { Db, DualSql } from "../db/index.js"; +import { dbRun } from "../db/index.js"; import { deflateSync } from "node:zlib"; import type { AccessInfo } from "../types/index.js"; import { consumeCode, CodeError, createDownloadGrant } from "../codes/service.js"; @@ -258,7 +259,13 @@ export async function generateChibiImage( // 3. 生成图片 const image = await generateImage(prompt, req); - // 4. 写入一次性下载授权凭证 + // 4. 写入生成记录(含 image_data) + await dbRun(db, { + sqlite: "INSERT INTO chibi_generations (code, category, subtype, grid_size, color_count, status, image_data) VALUES (?, ?, ?, ?, ?, 'completed', ?)", + pg: "INSERT INTO chibi_generations (code, category, subtype, grid_size, color_count, status, image_data) VALUES ($1, $2, $3, $4, $5, 'completed', $6)", + } satisfies DualSql, [req.code, req.category, req.subtype, req.gridSize, req.colorCount, image]); + + // 5. 写入一次性下载授权凭证 const downloadGrant = await createDownloadGrant(db, req.code); return { image, downloadGrant, access }; diff --git a/perler-lab-server/src/chibi/routes.ts b/perler-lab-server/src/chibi/routes.ts index b5134a1..d9b7c9f 100644 --- a/perler-lab-server/src/chibi/routes.ts +++ b/perler-lab-server/src/chibi/routes.ts @@ -1,14 +1,27 @@ import { Router } from "express"; import type { Request, Response } from "express"; import type { Db } from "../db/index.js"; -import { getDb } from "../db/index.js"; +import { getDb, dbAll } from "../db/index.js"; import { generateChibiImage, ChibiError, type GenerateRequest } from "./generate.js"; import { findTemplate, type ChibiCategory, type Composition } from "./prompts.js"; import { createRateLimiter, RATE_LIMITS } from "../security/rate-limit.js"; +import { CODE_FORMAT } from "../codes/service.js"; const CATEGORIES: readonly ChibiCategory[] = ["landscape", "person", "pet", "object", "food"]; const COMPOSITIONS: readonly Composition[] = ["主体特写", "半幅构图", "完整构图"]; +/** 行类型:chibi_generations 查询结果。 */ +interface HistoryRow { + id: number; + category: string; + subtype: string; + grid_size: number; + color_count: number; + status: string; + image_data: string | null; + created_at: string; +} + /** Resolve the database instance. */ function resolveDb(injected?: Db): Db { return injected ?? getDb(); @@ -114,5 +127,54 @@ export function createChibiRouter(injectedDb?: Db): Router { } }); + /** + * GET /api/chibi/history?code=XXX — 查询该兑换码最近 7 天的生成记录(倒序,最多 50 条)。 + * 响应: { items: [{ id, category, subtype, gridSize, colorCount, status, createdAt, image }] } + */ + router.get("/history", async (req: Request, res: Response): Promise => { + try { + const codeParam = req.query.code; + const code = typeof codeParam === "string" ? codeParam.trim().toUpperCase() : ""; + if (!code) { + res.status(400).json({ error: "请输入兑换码" }); + return; + } + if (!CODE_FORMAT.test(code)) { + res.status(400).json({ error: "兑换码格式不正确" }); + return; + } + + const db = resolveDb(injectedDb); + const items = await dbAll(db, { + sqlite: `SELECT id, category, subtype, grid_size, color_count, status, image_data, created_at + FROM chibi_generations + WHERE code = ? AND created_at >= datetime('now', '-7 days') + ORDER BY created_at DESC, id DESC + LIMIT 50`, + pg: `SELECT id, category, subtype, grid_size, color_count, status, image_data, created_at + FROM chibi_generations + WHERE code = $1 AND created_at >= now() - interval '7 days' + ORDER BY created_at DESC, id DESC + LIMIT 50`, + }, [code]); + + res.status(200).json({ + items: items.map((row) => ({ + id: row.id, + category: row.category, + subtype: row.subtype, + gridSize: row.grid_size, + colorCount: row.color_count, + status: row.status, + createdAt: row.created_at, + image: row.image_data, + })), + }); + } catch (err) { + console.error("GET /api/chibi/history error:", err); + res.status(500).json({ error: "服务器内部错误,请稍后重试" }); + } + }); + return router; } \ No newline at end of file diff --git a/perler-lab-server/src/db/index.ts b/perler-lab-server/src/db/index.ts index 6462027..57d4666 100644 --- a/perler-lab-server/src/db/index.ts +++ b/perler-lab-server/src/db/index.ts @@ -112,10 +112,11 @@ async function initPg(config?: PgConfig): Promise { return pool; } -/** SQLite 迁移:整段 DDL + showcase_works 规格列补齐(幂等)。 */ +/** SQLite 迁移:整段 DDL + showcase_works 规格列补齐(幂等)+ chibi_generations 列补齐。 */ function runSqliteMigrations(db: SqliteDb): void { db.exec(SCHEMA_SQL_SQLITE); migrateShowcaseSpecSqlite(db); + migrateChibiGenerationsSqlite(db); } /** PostgreSQL 迁移:逐条执行 DDL + showcase_works 规格列补齐(information_schema)。 */ @@ -128,6 +129,7 @@ async function runPgMigrations(pool: PgDb): Promise { await pool.query(stmt); } await migrateShowcaseSpecPg(pool); + await migrateChibiGenerationsPg(pool); } /** @@ -180,6 +182,35 @@ async function migrateShowcaseSpecPg(pool: PgDb): Promise { } } +/** 幂等迁移:为旧库 chibi_generations 补齐 image_data 列(SQLite 版)。 */ +function migrateChibiGenerationsSqlite(db: SqliteDb): void { + const columns = new Set( + (db.prepare("PRAGMA table_info(chibi_generations)").all() as Array<{ name: string }>).map( + (col) => col.name, + ), + ); + if (columns.size === 0) return; + if (!columns.has("image_data")) { + db.exec("ALTER TABLE chibi_generations ADD COLUMN image_data TEXT"); + } +} + +/** 幂等迁移:为旧库 chibi_generations 补齐 image_data 列(PostgreSQL 版)。 */ +async function migrateChibiGenerationsPg(pool: PgDb): Promise { + const reg = await pool.query("SELECT to_regclass('public.chibi_generations') AS reg"); + if (reg.rows[0]?.reg === null) return; + + const cols = await pool.query( + "SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'chibi_generations'", + ); + const columns = new Set( + (cols.rows as ReadonlyArray<{ column_name: string }>).map((c) => c.column_name), + ); + if (!columns.has("image_data")) { + await pool.query("ALTER TABLE chibi_generations ADD COLUMN image_data TEXT"); + } +} + /** * Get the active database instance. Throws if not initialized. * 生产返回 pg Pool;sqlite 文件模式返回 Database。 diff --git a/perler-lab-server/src/db/schema.ts b/perler-lab-server/src/db/schema.ts index ef721a1..f2f2aba 100644 --- a/perler-lab-server/src/db/schema.ts +++ b/perler-lab-server/src/db/schema.ts @@ -49,6 +49,7 @@ CREATE TABLE IF NOT EXISTS chibi_generations ( grid_size INTEGER NOT NULL, color_count INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', + image_data TEXT, created_at TEXT NOT NULL DEFAULT (datetime('now')) ); @@ -204,6 +205,7 @@ CREATE TABLE IF NOT EXISTS chibi_generations ( grid_size INTEGER NOT NULL, color_count INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', + image_data TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); diff --git a/perler-lab-server/src/tests/chibi.test.ts b/perler-lab-server/src/tests/chibi.test.ts index b22ef99..1c8bbc0 100644 --- a/perler-lab-server/src/tests/chibi.test.ts +++ b/perler-lab-server/src/tests/chibi.test.ts @@ -138,3 +138,68 @@ describe("POST /api/chibi/generate 路由", () => { expect(res.body.error).toBe("请输入兑换码"); }); }); + +describe("GET /api/chibi/history 路由", () => { + it("缺少 code 返回 400", async () => { + const { db } = setupDb(); + const app = createApp(db); + const res = await request(app).get("/api/chibi/history"); + + expect(res.status).toBe(400); + expect(res.body.error).toBe("请输入兑换码"); + }); + + it("格式不正确返回 400", async () => { + const { db } = setupDb(); + const app = createApp(db); + const res = await request(app).get("/api/chibi/history?code=SHORT"); + + expect(res.status).toBe(400); + expect(res.body.error).toBe("兑换码格式不正确"); + }); + + it("无记录返回空 items", async () => { + const { db, code } = setupDb(); + const app = createApp(db); + const res = await request(app).get(`/api/chibi/history?code=${code}`); + + expect(res.status).toBe(200); + expect(res.body.items).toEqual([]); + }); + + it("有生成记录时按倒序返回 items(含 image)", async () => { + const { db, code } = setupDb(5); + const app = createApp(db); + + // 触发两次生成,写入两条记录 + await request(app).post("/api/chibi/generate").send(baseRequest(code)); + await request(app).post("/api/chibi/generate").send(baseRequest(code)); + + const res = await request(app).get(`/api/chibi/history?code=${code}`); + + expect(res.status).toBe(200); + expect(Array.isArray(res.body.items)).toBe(true); + expect(res.body.items.length).toBe(2); + + // 最新一条在前 + const [latest, earlier] = res.body.items; + expect(latest.createdAt >= earlier.createdAt).toBe(true); + + // 字段映射:grid_size → gridSize,image_data → image + expect(latest).toMatchObject({ + category: "pet", + subtype: "cat", + gridSize: 48, + colorCount: 16, + status: "completed", + }); + expect(typeof latest.image).toBe("string"); + expect(latest.image).toContain("data:image/png;base64,"); + + // code 不存在的兑换码无记录 + const other = setupDb().code; + const empty = await request(app).get(`/api/chibi/history?code=${other}`); + expect(empty.status).toBe(200); + expect(empty.body.items).toEqual([]); + }); +});