Commit 037b08db by liimin

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

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