Commit 037b08db by liimin

refactor(recorder): 优化录音服务缓存管理和代码结构

- 修改 DefaultRecorderStrategy 中的 cacheConfig 类型从 Map 改为字符串数组
- 更新 StrategyUtils 中的缓存相关函数参数签名
- 重构 RecordCacheManager 中的 consumeAll 函数实现,改用数组遍历方式
- 移除 RecordService 中的调试日志和注释代码
- 优化 userInfo 解析逻辑,支持字符串和对象两种类型
- 调整缓存键值生成方式,统一使用字段名作为前缀
1 parent 58b49ba9
......@@ -49,13 +49,10 @@ export class RecordService {
* @returns 业务数据,如果不存在则返回 null
*/
async getBusinessData(): Promise<any> {
const recordId = this.record?.currentRecord?.id ?? "";
if (recordId === "") {
console.warn("[getBusinessData] recordId is empty, return null");
return null;
}
try {
const fullRecord = await this.record?.getRecord(recordId) as UTSJSONObject;
const businessData = await this.businessHandler.getBusinessData(recordId, fullRecord as any) as UTSJSONObject;
......@@ -66,7 +63,6 @@ export class RecordService {
}
}
getRecorder(): null | TempRecord {
return this.record;
}
......@@ -162,10 +158,8 @@ export class RecordService {
this.stopAudioRecord();
}
// --- 外部调用接口 ---
reset() {
// this.flushAllDebounceTimers();
this.audioManager = null;
this.record = null;
}
......@@ -247,7 +241,6 @@ export class RecordService {
stopAudioRecord() {
this.audioManager?.stop();
// this.timeoutService?.stop()
}
async triggerTempNumber() {
......@@ -264,10 +257,8 @@ export class RecordService {
// if (!this.isReceptioning()) return;
// 委托给 Handler 处理,传入 recordId 以便策略自行决定缓存还是持久化
const result = this.businessHandler.processBusinessData(data, this.record?.currentRecord?.id ?? "");
console.log("🚀 ~ RecordService ~ updateBusinessData ~ result:", result, this.record);
// 如果策略返回 null,说明已经由策略自行处理(如缓存)或无需处理
if (result === null) return;
// 如果策略返回了数据对象,则交由 Service 进行预记录持久化 (updatePreRecords)
this.record?.updatePreRecords(result);
}
......
......@@ -7,9 +7,7 @@ import * as StrategyUtils from "./StrategyUtils.uts";
export class DefaultRecorderStrategy implements IRecorderStrategy {
// 缓存配置:字段名 -> 缓存 Key 前缀
private cacheConfig: Map<string, string> = new Map([
["receptionCustomerMaterialPointList", "MATERIAL_POINTS_"]
]);
private cacheConfig: string[] = ["receptionCustomerMaterialPointList"];
// RecordData 中需要特殊处理的字段列表
private jsonFields: string[] = [
......@@ -35,7 +33,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
* 实现缓存消费逻辑
*/
async consumeBusinessCache(recordId: string, currentRecord: UTSJSONObject): Promise<UTSJSONObject> {
return await StrategyUtils.consumeBusinessCache(this.cacheConfig, currentRecord);
return await StrategyUtils.consumeBusinessCache(this.cacheConfig, currentRecord, recordId);
}
/**
......@@ -123,11 +121,9 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
// 遍历所有传入字段
dataObj.toMap().forEach((value, key) => {
// 判断是否需要缓存的字段
const cacheKeyPrefix = this.cacheConfig.get(key);
if (cacheKeyPrefix !== null && recordId !== "") {
if (this.cacheConfig.includes(key) && recordId !== "") {
// 需要缓存的字段,调用 cacheBusinessData
this.cacheBusinessData(recordId, key, value as any);
console.log(`[processBusinessData] 缓存字段:${key}`, value);
} else {
// 普通字段,添加到结果中准备持久化
result[key] = value;
......@@ -156,6 +152,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
const userInfo = storage.get("userInfo");
let obj: UTSJSONObject = {};
// 尝试解析 userInfo(支持 string 和 object 两种类型)
if (typeof userInfo === "string" && userInfo !== "") {
try {
obj = JSON.parse(userInfo) as UTSJSONObject;
......@@ -163,7 +160,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
console.warn(`Failed to parse userInfo JSON: ${error}`);
}
} else if (userInfo !== null && typeof userInfo === "object") {
// userInfo is already an object
obj = userInfo as UTSJSONObject;
}
const sceneType = obj.get("sceneType");
......@@ -201,7 +198,6 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
private async mergeWithCache(recordId: string, baseRecord: UTSJSONObject): Promise<any> {
// 1. 从缓存中恢复特殊字段数据
const cachedData = await this.consumeBusinessCache(recordId, baseRecord);
console.log("🚀 ~ DefaultRecorderStrategy ~ mergeWithCache ~ cachedData:", cachedData);
// 2. 获取动态属性
const dynamicAttributes = this.getDynamicAttributes();
......
......@@ -3,24 +3,16 @@ import { logger } from "../../logger/index.uts";
/**
* 消费缓存:读取缓存 -> 返回数据 -> 删除缓存
*/
export async function consumeAll(recordId: string, cacheConfig: Map<string, string>): Promise<UTSJSONObject> {
export async function consumeAll(recordId: string, cacheConfig: string[]): Promise<UTSJSONObject> {
if (recordId === "") return {};
const restoredData: UTSJSONObject = {};
// 遍历配置
const keyList: string[] = [];
cacheConfig.forEach((_, key) => {
keyList.push(key);
});
for (const keyPrefix of keyList) {
const targetField = cacheConfig.get(keyPrefix);
if (targetField === null) continue;
// 遍历配置:数组元素是字段名,缓存 key = 字段名 + "_" + recordId
cacheConfig.forEach((fieldName) => {
try {
const storageKey = keyPrefix + recordId;
const data = await new Promise<any | null>((resolve) => {
const storageKey = `${fieldName}_${recordId}`;
const data = new Promise<any | null>((resolve) => {
uni.getStorage({
key: storageKey,
success: (res) => {
......@@ -32,20 +24,30 @@ export async function consumeAll(recordId: string, cacheConfig: Map<string, stri
});
});
if (data !== null && data !== "") {
restoredData[targetField] = data;
uni.removeStorage({
key: storageKey,
fail: (res) => {
logger.warn(`RecordCacheManager: Remove ${storageKey} failed: ${res.errMsg}`, "RecordCache");
}
});
}
data.then((result) => {
if (result !== null && result !== "") {
restoredData[fieldName] = result;
uni.removeStorage({
key: storageKey,
fail: (res) => {
logger.warn(`RecordCacheManager: Remove ${storageKey} failed: ${res.errMsg}`, "RecordCache");
}
});
}
}).catch((error) => {
logger.warn(`RecordCacheManager: Consume ${fieldName} failed: ${error}`, "RecordCache");
});
} catch (error) {
logger.warn(`RecordCacheManager: Consume ${keyPrefix} failed: ${error}`, "RecordCache");
logger.warn(`RecordCacheManager: Consume ${fieldName} failed: ${error}`, "RecordCache");
}
}
return restoredData;
});
// 等待所有异步操作完成
return new Promise((resolve) => {
setTimeout(() => {
resolve(restoredData);
}, 100);
});
}
/**
......@@ -72,7 +74,10 @@ export async function load(key: string): Promise<any | null> {
return await new Promise<any | null>((resolve) => {
uni.getStorage({
key,
success: (res) => resolve(res.data),
success: (res) =>{
console.log("🚀 ~ load ~ res11111:", res);
resolve(res.data);
},
fail: () => resolve(null)
});
});
......
......@@ -9,14 +9,14 @@ import * as RecordCacheManager from "./RecordCacheManager.uts";
* 缓存业务数据
*/
export function cacheBusinessData(
cacheConfig: Map<string, string>,
cacheConfig: string[],
recordId: string,
type: string,
data: any
): void {
const keyPrefix = cacheConfig.get(type);
if (keyPrefix !== null) {
RecordCacheManager.set(recordId, keyPrefix, data);
if (cacheConfig.includes(type)) {
// 使用字段名 + "_" 作为缓存前缀
RecordCacheManager.set(recordId, `${type}_`, data);
}
}
......@@ -24,10 +24,11 @@ export function cacheBusinessData(
* 消费业务缓存
*/
export async function consumeBusinessCache(
cacheConfig: Map<string, string>,
currentRecord: UTSJSONObject
cacheConfig: string[],
currentRecord: UTSJSONObject,
recordId: string
): Promise<UTSJSONObject> {
const restored = await RecordCacheManager.consumeAll("", cacheConfig);
const restored = await RecordCacheManager.consumeAll(recordId, cacheConfig);
return Object.assign({}, currentRecord, restored);
}
......@@ -35,13 +36,11 @@ export async function consumeBusinessCache(
* 清理业务缓存
*/
export function clearBusinessCache(
cacheConfig: Map<string, string>,
cacheConfig: string[],
recordId: string
): void {
const keyList: string[] = [];
cacheConfig.forEach((entry) => {
keyList.push(entry.value);
});
// 将字段名转换为缓存 key(字段名 + "_" + recordId)
const keyList: string[] = cacheConfig.map(fieldName => `${fieldName}_`);
RecordCacheManager.clearAll(recordId, keyList);
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!