feat: V1.1 批次入库——色号表SEO页/Showcase/图纸库/帮助中心/JSON-LD/CI门禁/竞品分析
This commit is contained in:
1 parent
40e2342a02
commit
f53f0a2b25
104 files changed
+21760
-157
No files matched your search
@@ -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";
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
Reference in new issue
Block a user