73d56bddb8
- growth模块:新增游客承接、行为漏斗、推荐实验和站内生命周期运营 - 额度账本:事务预占、幂等结算、全站并发与字符预算保护 - 聊天与记忆:接入回答反馈、可控记忆和持久化异步提取 - 迁移020与回归:覆盖账号隔离、计数器死锁和真实MySQL并发场景
48 lines
1.8 KiB
TypeScript
48 lines
1.8 KiB
TypeScript
/** 登录账号资料与 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],
|
|
);
|
|
const parsed = parseDigitalProfile(profile?.body);
|
|
return account.startsWith("guest:")
|
|
? { ...parsed, nsfwEnabled: false }
|
|
: parsed;
|
|
}
|
|
|
|
/** 原子合并 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,
|
|
);
|
|
}
|