feat(nsfw): 持久化账号偏好并接入生成控制
- digital.profile.ts: 未保存偏好时默认开启,原子合并 JSON 保留其他资料 - digital.controller.ts、digital.users.ts: 接入本人和管理员偏好读写、事务及审计 - digital.chat.ts、digital.prompt.ts、digital.suggestions.ts: 各生成入口读取服务端账号偏好,保留游客鉴权 - tests/digital-*.test.ts: 覆盖默认值、关闭保留、旧客户端兼容与越权拦截 - README.md: 同步模块职责和发布要求
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
/** 登录账号资料与 NSFW 偏好;缺省开启,局部写入不会覆盖其他资料字段。 */
|
||||
import { z } from "zod";
|
||||
import type { PoolConnection } from "mysql2/promise";
|
||||
import { json, rows, write } from "./digital.repository";
|
||||
|
||||
/** 旧账号无需回填;仅缺失的内容偏好采用默认开启,显式关闭继续保留。 */
|
||||
export const digitalProfileSchema = z.object({
|
||||
favorites: z.array(z.string()).default([]),
|
||||
persona: z.string().default(""),
|
||||
userName: z.string().default("旅人"),
|
||||
nsfwEnabled: z.boolean().default(true),
|
||||
});
|
||||
|
||||
/** 账号级偏好不复制到会话,已有会话在下一次生成时读取最新值。 */
|
||||
export type DigitalProfile = z.infer<typeof digitalProfileSchema>;
|
||||
|
||||
/** 兼容数据库返回 JSON 字符串、对象和不存在的资料记录。 */
|
||||
export function parseDigitalProfile(value: unknown): DigitalProfile {
|
||||
return digitalProfileSchema.parse(json(value) ?? {});
|
||||
}
|
||||
|
||||
/** 调用方必须先鉴权,并只传入已验证的账号命名空间。 */
|
||||
export async function getDigitalProfile(
|
||||
account: string,
|
||||
): Promise<DigitalProfile> {
|
||||
const [profile] = await rows<{ body: unknown }>(
|
||||
"SELECT body FROM dh_profiles WHERE account=?",
|
||||
[account],
|
||||
);
|
||||
return parseDigitalProfile(profile?.body);
|
||||
}
|
||||
|
||||
/** 原子合并 JSON 字段,旧客户端保存收藏或管理员改开关不会覆盖对方的字段。 */
|
||||
export async function mergeDigitalProfile(
|
||||
account: string,
|
||||
patch: Partial<DigitalProfile>,
|
||||
connection?: PoolConnection,
|
||||
): Promise<void> {
|
||||
await write(
|
||||
"INSERT INTO dh_profiles(account,body) VALUES (?,?) ON DUPLICATE KEY UPDATE body=JSON_MERGE_PATCH(body,VALUES(body))",
|
||||
[account, JSON.stringify(patch)],
|
||||
connection,
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user