feat(chibi): GET /api/chibi/history 近7天生成记录 + image_data 幂等迁移 + 4测试

This commit is contained in:
Sisyphus committed 2026-08-23 02:17:16 +08:00
1 parent 125c20906c
commit b33d5c466d
5 files changed
+171 -4

No files matched your search

+9 -2
View File
@@ -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 };
+63 -1
View File
@@ -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<void> => {
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<HistoryRow>(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;
}
+32 -1
View File
@@ -112,10 +112,11 @@ async function initPg(config?: PgConfig): Promise<PgDb> {
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<void> {
await pool.query(stmt);
}
await migrateShowcaseSpecPg(pool);
await migrateChibiGenerationsPg(pool);
}
/**
@@ -180,6 +182,35 @@ async function migrateShowcaseSpecPg(pool: PgDb): Promise<void> {
}
}
/** 幂等迁移:为旧库 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<void> {
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。
+2
View File
@@ -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()
);
+65
View File
@@ -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([]);
});
});