Commit d25aea67 by liimin

refactor(recorder): 重构录音服务和存储工具类

- 移除 RecordService 中的 initDto 方法和相关初始化逻辑
- 简化 TempRecord 构造函数,移除 newRecord 属性和相关合并逻辑
- 优化 DefaultRecorderStrategy 中的动态属性获取逻辑
- 重构 storage 工具类,添加 get、parse、once 等便捷方法
- 更新存储类的文档注释和方法实现
- 统一时间获取方式,使用 Date.now() 替代 new Date().getTime()
1 parent 70753e8d
...@@ -75,14 +75,8 @@ export class RecordService { ...@@ -75,14 +75,8 @@ export class RecordService {
(res) => { this.onAudioStop(res); }, (res) => { this.onAudioStop(res); },
(err) => { this.onAudioError(err); } (err) => { this.onAudioError(err); }
); );
this.initDto();
this.record = new TempRecord( this.record = new TempRecord(
this.tempRecordDto,
() => { this.triggerTempNumber(); } () => { this.triggerTempNumber(); }
// () => {
// // 委托给当前的业务策略获取动态属性
// return this.businessHandler.getDynamicAttributes();
// }
); );
this.timeoutService = TimeoutService.getInstance(async () => { this.timeoutService = TimeoutService.getInstance(async () => {
await this.stopAudio(); await this.stopAudio();
...@@ -93,17 +87,6 @@ export class RecordService { ...@@ -93,17 +87,6 @@ export class RecordService {
handleError(error, "RecordService", "【录音服务 RecordService】 == 初始化异常:"); handleError(error, "RecordService", "【录音服务 RecordService】 == 初始化异常:");
} }
} }
// initReception() {
// commit("updateBookList", [] as UTSJSONObject[]);
// commit("updateCustomerInfo", null as null | UTSJSONObject);
// commit("updateReceptionStatus", "");
// }
// initWatchers() {}
initDto() {
// initialize as RecordData or null
this.tempRecordDto = null;
}
async isPermission(hintText: string = "为了记录语音通话,请打开录音权限"): Promise<boolean> { async isPermission(hintText: string = "为了记录语音通话,请打开录音权限"): Promise<boolean> {
return await ensurePermission("Microphone", hintText); return await ensurePermission("Microphone", hintText);
......
...@@ -8,7 +8,6 @@ import { IRecordDataBase, RecordData, RecordFile } from "./types"; ...@@ -8,7 +8,6 @@ import { IRecordDataBase, RecordData, RecordFile } from "./types";
class TempRecord { class TempRecord {
_isDestroyed = false; // 新增销毁标志位 _isDestroyed = false; // 新增销毁标志位
dbRecord: DBRecord | null = null; dbRecord: DBRecord | null = null;
newRecord: null | RecordData = null;
onTempRecordNumberChanged: (() => void) | null = null; onTempRecordNumberChanged: (() => void) | null = null;
path = ""; path = "";
record: null | RecordData = null; record: null | RecordData = null;
...@@ -30,8 +29,7 @@ class TempRecord { ...@@ -30,8 +29,7 @@ class TempRecord {
return this.dbRecord; return this.dbRecord;
} }
constructor(record: null | RecordData, onTempRecordNumberChanged: (() => void) | null) { constructor(onTempRecordNumberChanged: (() => void) | null) {
this.newRecord = record;
// this.dbRecord = uni.$dbRecord // 延迟获取,避免初始化顺序问题 // this.dbRecord = uni.$dbRecord // 延迟获取,避免初始化顺序问题
this.onTempRecordNumberChanged = onTempRecordNumberChanged; this.onTempRecordNumberChanged = onTempRecordNumberChanged;
} }
...@@ -52,7 +50,7 @@ class TempRecord { ...@@ -52,7 +50,7 @@ class TempRecord {
// 合并逻辑:新记录默认值 <- 现有记录 (如有) // 合并逻辑:新记录默认值 <- 现有记录 (如有)
// 使用 Object.assign 简化合并,最后统一深拷贝 // 使用 Object.assign 简化合并,最后统一深拷贝
const merged = Object.assign({}, newRec, this.newRecord ?? {}); const merged = Object.assign({}, newRec);
const res = deepClone<RecordData>(merged); const res = deepClone<RecordData>(merged);
if (res === null) { if (res === null) {
......
...@@ -156,24 +156,24 @@ export class DefaultRecorderStrategy implements IRecorderStrategy { ...@@ -156,24 +156,24 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
* 获取动态业务属性 * 获取动态业务属性
*/ */
private getDynamicAttributes(): UTSJSONObject { private getDynamicAttributes(): UTSJSONObject {
const userInfo = storage.get("userInfo"); const obj = storage.get("userInfo");
console.log("🚀 ~ DefaultRecorderStrategy ~ getDynamicAttributes ~ userInfo:", userInfo); const loginPhone = obj.get("loginPhone");
let obj: UTSJSONObject = {}; const merchantId = obj.get("shopMerchantId");
const merchantName = obj.get("merchantName");
// 尝试解析 userInfo(支持 string 和 object 两种类型) const staffUuid = obj.get("staffUuid");
if (typeof userInfo === "string" && userInfo !== "") { const staffName = obj.get("staffName");
try { const channelType = obj.get("channelType");
obj = JSON.parse(userInfo) as UTSJSONObject;
} catch (error) {
console.warn(`Failed to parse userInfo JSON: ${error}`);
}
} else if (userInfo !== null && typeof userInfo === "object") {
obj = userInfo as UTSJSONObject;
}
const sceneType = obj.get("sceneType"); const sceneType = obj.get("sceneType");
const { deviceId: appCode } = uni.getDeviceInfo();
return { return {
bussinessType: this.getBussinessType(sceneType) appCode,
bussinessType: this.getBussinessType(sceneType),
loginPhone,
merchantId,
merchantName,
staffUuid,
staffName,
channelType,
}; };
} }
......
...@@ -9,18 +9,51 @@ const EXPIRES_SUFFIX = "_deadtime"; ...@@ -9,18 +9,51 @@ const EXPIRES_SUFFIX = "_deadtime";
*/ */
class Storage { class Storage {
/** /**
* 获取存储数据 * 清空所有存储数据
*
* 警告:此操作会删除所有本地存储数据,请谨慎使用
*
* @example
* storage.clear(); // 清空所有数据
*/
clear() {
uni.clearStorageSync();
}
/**
* 获取存储数据并自动解析为 UTSJSONObject
*
* 从 storage 中获取指定 key 的数据,如果是字符串会自动解析为 JSON
* 支持 string 和 object 两种数据格式
* *
* @param key 存储键名 * @param key 存储键名
* @returns 存储的数据,如果不存在则返回 null * @returns 解析后的 UTSJSONObject 对象,如果获取失败则返回空对象
* *
* @example * @example
* const userData = storage.get('user'); * // 获取用户信息
* if (userData != null) { * const userInfo = storage.get('userInfo');
* console.log(userData); * const loginPhone = userInfo.get('loginPhone');
* } *
* @example
* // 获取配置数据
* const config = storage.get('config');
* const value = config.get('someKey');
*/
get(key: string): UTSJSONObject {
const data = uni.getStorageSync(key);
return this._parseData(data);
}
/**
* 获取存储的原始数据
*
* @param key 存储键名
* @returns 存储的原始数据,不做任何处理
*
* @example
* const rawData = storage.getRaw('user');
*/ */
get(key: string): any | null { getRaw(key: string): any | null {
return uni.getStorageSync(key); return uni.getStorageSync(key);
} }
...@@ -52,32 +85,6 @@ class Storage { ...@@ -52,32 +85,6 @@ class Storage {
} }
/** /**
* 设置存储数据
*
* @param key 存储键名
* @param value 要存储的数据,支持任意类型
* @param expires 过期时间(秒),默认为0表示永不过期
*
* @example
* // 存储永久数据
* storage.set('user', { name: '张三', age: 25 }, 0);
*
* // 存储5分钟后过期的数据
* storage.set('token', 'abc123', 300);
*/
set(key: string, value: any, expires: number): void {
// 存储主要数据
uni.setStorageSync(key, value);
// 如果设置了过期时间,则存储过期时间戳
if (expires > 0) {
// 计算过期时间戳:当前时间 + 过期时间(秒转毫秒)
const expireTime = new Date().getTime() + expires * 1000;
uni.setStorageSync(`${key}${EXPIRES_SUFFIX}`, expireTime);
}
}
/**
* 检查数据是否已过期 * 检查数据是否已过期
* *
* @param key 存储键名 * @param key 存储键名
...@@ -90,7 +97,7 @@ class Storage { ...@@ -90,7 +97,7 @@ class Storage {
*/ */
isExpired(key: string): boolean { isExpired(key: string): boolean {
// 获取过期时间戳 // 获取过期时间戳
const value = uni.getStorageSync(`${key}${EXPIRES_SUFFIX}`) as number | null; const value = uni.getStorageSync(`${key}${EXPIRES_SUFFIX}`) as null | number;
// 如果没有设置过期时间,视为已过期 // 如果没有设置过期时间,视为已过期
if (value == null) { if (value == null) {
...@@ -98,7 +105,53 @@ class Storage { ...@@ -98,7 +105,53 @@ class Storage {
} }
// 比较过期时间戳与当前时间,判断是否过期 // 比较过期时间戳与当前时间,判断是否过期
return value - new Date().getTime() <= 0; return value - Date.now() <= 0;
}
/**
* 获取数据后立即删除(一次性读取)
*
* 适用于临时数据、一次性令牌等场景
* 读取后数据会被自动删除,确保数据的一次性使用
*
* @param key 存储键名
* @returns 存储的数据,如果不存在则返回 null
*
* @example
* const tempToken = storage.once('temp_token');
* // tempToken 使用后,存储中的 temp_token 已被删除
*/
once(key: string): any | null {
// 先获取数据
const value = this.get(key);
// 立即删除数据
this.remove(key);
// 返回获取到的数据
return value;
}
/**
* 解析存储的数据为 UTSJSONObject
*
* 从 storage 中获取指定 key 的数据并解析为 UTSJSONObject 对象
* 支持 string 和 object 两种数据格式,自动处理 JSON 解析
*
* @param key 存储键名
* @returns 解析后的 UTSJSONObject 对象,如果获取失败则返回空对象
*
* @example
* // 解析用户信息
* const userInfo = storage.parse('userInfo');
* const loginPhone = userInfo.get('loginPhone');
*
* @example
* // 解析其他任意数据
* const config = storage.parse('config');
* const value = config.get('someKey');
*/
parse(key: string): UTSJSONObject {
const data = this.get(key);
return this._parseData(data);
} }
/** /**
...@@ -120,37 +173,52 @@ class Storage { ...@@ -120,37 +173,52 @@ class Storage {
} }
/** /**
* 清空所有存储数据 * 设置存储数据
* *
* 警告:此操作会删除所有本地存储数据,请谨慎使用 * @param key 存储键名
* @param value 要存储的数据,支持任意类型
* @param expires 过期时间(秒),默认为0表示永不过期
* *
* @example * @example
* storage.clear(); // 清空所有数据 * // 存储永久数据
* storage.set('user', { name: '张三', age: 25 }, 0);
*
* // 存储5分钟后过期的数据
* storage.set('token', 'abc123', 300);
*/ */
clear() { set(key: string, value: any, expires: number): void {
uni.clearStorageSync(); // 存储主要数据
uni.setStorageSync(key, value);
// 如果设置了过期时间,则存储过期时间戳
if (expires > 0) {
// 计算过期时间戳:当前时间 + 过期时间(秒转毫秒)
const expireTime = Date.now() + expires * 1000;
uni.setStorageSync(`${key}${EXPIRES_SUFFIX}`, expireTime);
}
} }
/** /**
* 获取数据后立即删除(一次性读取) * 解析数据的内部辅助方法
*
* 适用于临时数据、一次性令牌等场景
* 读取后数据会被自动删除,确保数据的一次性使用
* *
* @param key 存储键名 * @param data 要解析的数据
* @returns 存储的数据,如果不存在则返回 null * @returns 解析后的 UTSJSONObject 对象
*
* @example
* const tempToken = storage.once('temp_token');
* // tempToken 使用后,存储中的 temp_token 已被删除
*/ */
once(key: string): any | null { private _parseData(data: any | null): UTSJSONObject {
// 先获取数据 let obj: UTSJSONObject = {};
const value = this.get(key);
// 立即删除数据 // 支持 string 和 object 两种类型
this.remove(key); if (typeof data === "string" && data !== "") {
// 返回获取到的数据 try {
return value; obj = JSON.parse(data) as UTSJSONObject;
} catch (error) {
console.warn(`Failed to parse JSON: ${error}`);
}
} else if (data !== null && typeof data === "object") {
obj = data as UTSJSONObject;
}
return obj;
} }
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!