Files
perler-lab/perler-lab-server/src/chibi/routes.ts
T

118 lines
4.0 KiB
TypeScript

import { Router } from "express";
import type { Request, Response } from "express";
import type { Db } from "../db/index.js";
import { getDb } 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";
const CATEGORIES: readonly ChibiCategory[] = ["landscape", "person", "pet", "object", "food"];
const COMPOSITIONS: readonly Composition[] = ["主体特写", "半幅构图", "完整构图"];
/** Resolve the database instance. */
function resolveDb(injected?: Db): Db {
return injected ?? getDb();
}
/**
* Create the chibi router. Accepts an optional injected database for testing.
*
* POST /api/chibi/generate
* Request: { code, image, referenceImage?, category, subtype, gridSize,
* colorCount, composition, detailTags, customPrompt? }
* Response: 200 { image, access, downloadGrant }
* 400 / 402 / 500 / 502
*/
export function createChibiRouter(injectedDb?: Db): Router {
const router = Router();
// 防刷限流
const chibiLimiter = createRateLimiter(RATE_LIMITS.chibiGenerate)("chibi_generate");
router.post("/generate", chibiLimiter, async (req: Request, res: Response): Promise<void> => {
try {
const body = (req.body ?? {}) as Record<string, unknown>;
const code = typeof body.code === "string" ? body.code : "";
if (!code) {
res.status(400).json({ error: "请输入兑换码" });
return;
}
const image = typeof body.image === "string" ? body.image : "";
if (!image) {
res.status(400).json({ error: "请上传图片" });
return;
}
const referenceImage =
typeof body.referenceImage === "string" && body.referenceImage !== ""
? body.referenceImage
: undefined;
const category = body.category as ChibiCategory;
if (!CATEGORIES.includes(category)) {
res.status(400).json({ error: "未知的分类" });
return;
}
const subtype = typeof body.subtype === "string" ? body.subtype : "";
try {
findTemplate(category, subtype);
} catch {
res.status(400).json({ error: "未知的模板类型" });
return;
}
const composition = body.composition as Composition;
if (!COMPOSITIONS.includes(composition)) {
res.status(400).json({ error: "未知的构图方式" });
return;
}
const gridSize = Number(body.gridSize);
if (!Number.isInteger(gridSize) || gridSize < 16 || gridSize > 512) {
res.status(400).json({ error: "网格尺寸无效" });
return;
}
const colorCount = Number(body.colorCount);
if (!Number.isInteger(colorCount) || colorCount < 4 || colorCount > 64) {
res.status(400).json({ error: "颜色数量无效" });
return;
}
const detailTags = Array.isArray(body.detailTags)
? body.detailTags.filter((t): t is string => typeof t === "string")
: [];
const customPrompt =
typeof body.customPrompt === "string" && body.customPrompt.trim() !== ""
? body.customPrompt
: undefined;
const payload: GenerateRequest = {
code,
image,
referenceImage,
category,
subtype,
gridSize,
colorCount,
composition,
detailTags,
customPrompt,
};
const result = await generateChibiImage(resolveDb(injectedDb), payload);
res.status(200).json({
image: result.image,
access: result.access,
downloadGrant: result.downloadGrant,
});
} catch (err) {
if (err instanceof ChibiError) {
res.status(err.status).json({ error: err.message });
} else {
console.error("POST /api/chibi/generate error:", err);
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
}
}
});
return router;
}