/** 登录账号资料与 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; /** 兼容数据库返回 JSON 字符串、对象和不存在的资料记录。 */ export function parseDigitalProfile(value: unknown): DigitalProfile { return digitalProfileSchema.parse(json(value) ?? {}); } /** 调用方必须先鉴权,并只传入已验证的账号命名空间。 */ export async function getDigitalProfile( account: string, ): Promise { 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, connection?: PoolConnection, ): Promise { 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, ); }