Commit 0c1fb08a by liimin

refactor(recorder): 重构业务数据处理与缓存机制

- 将业务数据缓存逻辑从 RecordService 移至策略层,遵循单一职责原则
- 在 IRecorderStrategy 接口中新增缓存操作方法,使策略能够自主管理业务数据
- 修改 IBusinessDataHandler.handle 方法签名,增加 recordId 参数以支持策略级缓存决策
- 重构 DefaultRecorderStrategy 实现缓存写入、消费和清理逻辑
- 优化 RecordCache 使其支持通用缓存配置,便于策略扩展
- 统一使用严格相等运算符 (===) 替换松散相等运算符 (==)
- 修复注释拼写错误 (@Description 替换 @Descripttion)
- 更新 cspell 词典,添加缺失的技术词汇
1 parent a0bca4af
...@@ -2,7 +2,7 @@ import { startRecord, StartRecordOptions, StartRecordSuccess, stopRecord, StopRe ...@@ -2,7 +2,7 @@ import { startRecord, StartRecordOptions, StartRecordSuccess, stopRecord, StopRe
import { logger } from "../logger"; import { logger } from "../logger";
/* /*
* @Descripttion: * @Description:
* @version: 1.0.0 * @version: 1.0.0
* @Author: limin * @Author: limin
* @Date: 2024-12-04 18:17:23 * @Date: 2024-12-04 18:17:23
......
import type { IDBRecord, RecordData } from "./types"; import type { IDBRecord, RecordData } from "./types";
/* /*
* @Descripttion: * @Description:
* @version: 1.0.0 * @version: 1.0.0
* @Author: limin * @Author: limin
* @Date: 2025-01-02 18:34:39 * @Date: 2025-01-02 18:34:39
...@@ -43,7 +43,7 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -43,7 +43,7 @@ class DBRecord extends DBBase implements IDBRecord {
} }
static getInstance(): DBRecord { static getInstance(): DBRecord {
if (DBRecord.instance == null) { if (DBRecord.instance === null) {
DBRecord.instance = new DBRecord(); DBRecord.instance = new DBRecord();
} }
return DBRecord.instance; return DBRecord.instance;
...@@ -71,6 +71,10 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -71,6 +71,10 @@ class DBRecord extends DBBase implements IDBRecord {
return this.parseRecords(records); return this.parseRecords(records);
} }
getStrategy(): IRecorderStrategy {
return this.strategy;
}
/** /**
* 获取进行中/临时的接待记录 (recordStatus = 0) * 获取进行中/临时的接待记录 (recordStatus = 0)
*/ */
...@@ -112,7 +116,7 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -112,7 +116,7 @@ class DBRecord extends DBBase implements IDBRecord {
// 更好的做法是: // 更好的做法是:
// 1. setStrategy 改为 async (但这会破坏接口签名,如果有接口的话) // 1. setStrategy 改为 async (但这会破坏接口签名,如果有接口的话)
// 2. 在内部启动一个 async 任务,并捕获错误 // 2. 在内部启动一个 async 任务,并捕获错误
if (this.db != null) { if (this.db !== null) {
// 使用 IIFE 或 then/catch 处理异步 // 使用 IIFE 或 then/catch 处理异步
this.ensureColumns().catch(error => { this.ensureColumns().catch(error => {
logger.error(`DBRecord: setStrategy ensureColumns failed: ${error}`, "DBRecord"); logger.error(`DBRecord: setStrategy ensureColumns failed: ${error}`, "DBRecord");
...@@ -130,8 +134,8 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -130,8 +134,8 @@ class DBRecord extends DBBase implements IDBRecord {
const existingColumns = columnInfo.map((col: any): string => { const existingColumns = columnInfo.map((col: any): string => {
const c = col as UTSJSONObject; const c = col as UTSJSONObject;
const name = c.name; const name = c.name;
return (name != null ? name : "") as string; return (name !== null ? name : "") as string;
}).filter((name: string): boolean => name != ""); }).filter((name: string): boolean => name !== "");
logger.info(`DBRecord: existingColumns: ${JSON.stringify(existingColumns)}`, "DBRecord"); logger.info(`DBRecord: existingColumns: ${JSON.stringify(existingColumns)}`, "DBRecord");
...@@ -144,7 +148,7 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -144,7 +148,7 @@ class DBRecord extends DBBase implements IDBRecord {
const name = parts[0]; const name = parts[0];
// 简单的判断,如果 name 不为空且不在 existingColumns 中 // 简单的判断,如果 name 不为空且不在 existingColumns 中
if (name != "" && !existingColumns.includes(name)) { if (name !== "" && !existingColumns.includes(name)) {
// 重新组装 definition: 去掉 name,剩下的就是 definition // 重新组装 definition: 去掉 name,剩下的就是 definition
const definition = colDef.slice(name.length).trim(); const definition = colDef.slice(name.length).trim();
columnsToAdd.push({ name, definition }); columnsToAdd.push({ name, definition });
...@@ -200,7 +204,7 @@ class DBRecord extends DBBase implements IDBRecord { ...@@ -200,7 +204,7 @@ class DBRecord extends DBBase implements IDBRecord {
// 使用 JSON 转换是一种通用的方式 // 使用 JSON 转换是一种通用的方式
const recordStr = JSON.stringify(itemObj); const recordStr = JSON.stringify(itemObj);
const record = JSON.parse<RecordData>(recordStr); const record = JSON.parse<RecordData>(recordStr);
if (record != null) { if (record !== null) {
res.push(record); res.push(record);
} }
} catch (error) { } catch (error) {
......
...@@ -4,21 +4,11 @@ ...@@ -4,21 +4,11 @@
* @Author: limin * @Author: limin
* @Date: 2026-01-14 14:30:10 * @Date: 2026-01-14 14:30:10
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-03-06 14:22:59 * @LastEditTime: 2026-03-06 15:04:58
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\RecordCache.uts * @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\RecordCache.uts
*/ */
import { logger } from "../logger/index.uts"; import { logger } from "../logger/index.uts";
type CacheConfigItem = {
keyPrefix: string
targetField: string
}
const CACHE_CONFIG_MATERIAL_POINTS = {
keyPrefix: "MATERIAL_POINTS_", // Storage Key 前缀
targetField: "receptionCustomerMaterialPointList" // 对应的 Record 字段名
} as CacheConfigItem;
/** /**
* 记录缓存管理器 * 记录缓存管理器
* 统一管理大字段的暂存、合并与清理 * 统一管理大字段的暂存、合并与清理
...@@ -27,16 +17,16 @@ export default class RecordCache { ...@@ -27,16 +17,16 @@ export default class RecordCache {
/** /**
* 清理指定记录的所有缓存 * 清理指定记录的所有缓存
* @param {string} recordId * @param {string} recordId
* @param {string[]} keys - 需要清理的缓存 key 列表
*/ */
static clearAll(recordId: string) { static clearAll(recordId: string, keys: string[]) {
if (recordId == "") return; if (recordId === "") return;
const configs = [CACHE_CONFIG_MATERIAL_POINTS]; keys.forEach(keyPrefix => {
configs.forEach(config => {
try { try {
uni.removeStorage({ uni.removeStorage({
key: config.keyPrefix + recordId, key: keyPrefix + recordId,
fail: (res) => {} fail: () => {}
}); });
} catch {} } catch {}
}); });
...@@ -44,26 +34,31 @@ export default class RecordCache { ...@@ -44,26 +34,31 @@ export default class RecordCache {
/** /**
* 消费缓存:读取缓存 -> 返回数据 -> 删除缓存 * 消费缓存:读取缓存 -> 返回数据 -> 删除缓存
* @param {object} record - 记录对象 (仅用于获取ID) * @param {string} recordId - 记录 ID
* @param {Map<string, string>} cacheConfig - 缓存配置 Map<KeyPrefix, TargetField>
* @returns {object} 从缓存恢复的数据对象 * @returns {object} 从缓存恢复的数据对象
*/ */
static async consumeAll(record: any): Promise<UTSJSONObject> { static async consumeAll(recordId: string, cacheConfig: Map<string, string>): Promise<UTSJSONObject> {
const recordObj = record as UTSJSONObject; if (recordId === "") return {};
const recordId = recordObj.getString("id");
if (recordId == null) return {};
const restoredData: UTSJSONObject = {}; const restoredData: UTSJSONObject = {};
// 遍历配置 // 遍历配置
// 目前只有一个,直接硬编码处理,或者用 Object.values (UTS可能不支持) const keyList: string[] = [];
const configs = [CACHE_CONFIG_MATERIAL_POINTS]; // UTS Map iteration workaround: manually iterate using forEach on the map itself
cacheConfig.forEach((_, key) => {
for (const config of configs) { keyList.push(key);
});
for (const keyPrefix of keyList) {
const targetField = cacheConfig.get(keyPrefix);
if (targetField === null) continue;
try { try {
const key = config.keyPrefix + recordId; const storageKey = keyPrefix + recordId;
const data = await new Promise<any | null>((resolve) => { const data = await new Promise<any | null>((resolve) => {
uni.getStorage({ uni.getStorage({
key, key: storageKey,
success: (res) => { success: (res) => {
resolve(res.data); resolve(res.data);
}, },
...@@ -73,17 +68,17 @@ export default class RecordCache { ...@@ -73,17 +68,17 @@ export default class RecordCache {
}); });
}); });
if (data != null && data != "") { if (data !== null && data !== "") {
restoredData[config.targetField] = data; restoredData[targetField] = data;
uni.removeStorage({ uni.removeStorage({
key, key: storageKey,
fail: (res) => { fail: (res) => {
logger.warn(`RecordCacheManager: Remove ${key} failed: ${res.errMsg}`, "RecordCache"); logger.warn(`RecordCacheManager: Remove ${storageKey} failed: ${res.errMsg}`, "RecordCache");
} }
}); // 消费即焚 }); // 消费即焚
} }
} catch (error) { } catch (error) {
logger.warn(`RecordCacheManager: Consume ${config.keyPrefix} failed: ${error}`, "RecordCache"); logger.warn(`RecordCacheManager: Consume ${keyPrefix} failed: ${error}`, "RecordCache");
} }
} }
return restoredData; return restoredData;
...@@ -92,27 +87,21 @@ export default class RecordCache { ...@@ -92,27 +87,21 @@ export default class RecordCache {
/** /**
* 暂存数据 * 暂存数据
* @param {string} recordId - 记录ID * @param {string} recordId - 记录ID
* @param {string} type - 缓存类型 (key of CACHE_CONFIG) * @param {string} keyPrefix - 缓存 Key 前缀
* @param {any} data - 数据 * @param {any} data - 数据
*/ */
static set(recordId: string, type: string, data: any) { static set(recordId: string, keyPrefix: string, data: any) {
// UTS 中对象键访问需要 specific if (recordId === "" || keyPrefix === "") return;
let config: CacheConfigItem | null = null;
if (type == "MATERIAL_POINTS") {
config = CACHE_CONFIG_MATERIAL_POINTS;
}
if (recordId == "" || config == null) return;
try { try {
uni.setStorage({ uni.setStorage({
key: config.keyPrefix + recordId, key: keyPrefix + recordId,
data, data,
fail: (res) => { fail: (res) => {
logger.error(`RecordCacheManager: Set ${type} failed: ${res.errMsg}`, "RecordCache"); logger.error(`RecordCacheManager: Set ${keyPrefix} failed: ${res.errMsg}`, "RecordCache");
} }
}); });
} catch (error) { } catch (error) {
logger.error(`RecordCacheManager: Set ${type} failed: ${error}`, "RecordCache"); logger.error(`RecordCacheManager: Set ${keyPrefix} failed: ${error}`, "RecordCache");
} }
} }
} }
...@@ -111,7 +111,7 @@ export class RecordService { ...@@ -111,7 +111,7 @@ export class RecordService {
async isPermission(hintText: string = "为了记录语音通话,请打开录音权限"): Promise<boolean> { async isPermission(hintText: string = "为了记录语音通话,请打开录音权限"): Promise<boolean> {
return new Promise((resolve) => { return new Promise((resolve) => {
checkPermission("Microphone", (result) => { checkPermission("Microphone", (result) => {
if (result == "granted") { if (result === "granted") {
resolve(true); resolve(true);
} else { } else {
requestPermissions({ requestPermissions({
...@@ -147,7 +147,7 @@ export class RecordService { ...@@ -147,7 +147,7 @@ export class RecordService {
} }
isReceptioning(): boolean { isReceptioning(): boolean {
return (this.audioManager?.isRecording ?? false) || (this.record?.currentRecord?.endReasonType == 1); return (this.audioManager?.isRecording ?? false) || (this.record?.currentRecord?.endReasonType === 1);
} }
onAudioError(error: any) { onAudioError(error: any) {
...@@ -158,11 +158,11 @@ export class RecordService { ...@@ -158,11 +158,11 @@ export class RecordService {
async onAudioStart(res: StartRecordSuccess) { async onAudioStart(res: StartRecordSuccess) {
try { try {
// 安全检查:防止 Service 已重置导致空指针 // 安全检查:防止 Service 已重置导致空指针
if (this.audioManager == null) { if (this.audioManager === null) {
logger.warn("〖RecordService〗 == onAudioStart called but audioManager is null", "RecordService"); logger.warn("〖RecordService〗 == onAudioStart called but audioManager is null", "RecordService");
return; return;
} }
if (this.record == null) { if (this.record === null) {
logger.warn("〖RecordService〗 == onAudioStart called but record is null", "RecordService"); logger.warn("〖RecordService〗 == onAudioStart called but record is null", "RecordService");
return; return;
} }
...@@ -203,7 +203,7 @@ export class RecordService { ...@@ -203,7 +203,7 @@ export class RecordService {
} }
async onAudioStop(res: any) { async onAudioStop(res: any) {
if (this.audioManager?.isRecording == true) { if (this.audioManager?.isRecording === true) {
logger.info("【录音服务RecordService】 == 接待中,再次开启录音! ", "RecordService"); logger.info("【录音服务RecordService】 == 接待中,再次开启录音! ", "RecordService");
this.audioManager?.start(); this.audioManager?.start();
} else { } else {
...@@ -217,8 +217,8 @@ export class RecordService { ...@@ -217,8 +217,8 @@ export class RecordService {
this.stopAudioRecord(); this.stopAudioRecord();
} }
reportError(msg: string, errorMsg: string) { reportError(msg: string, error: any) {
logger.error({ msg: `【录音服务RecordService】 == ${msg}` }, "RecordService"); logger.error({ msg: `【录音服务RecordService】 == ${msg} error: ${error}` }, "RecordService");
} }
reset() { reset() {
...@@ -293,7 +293,7 @@ export class RecordService { ...@@ -293,7 +293,7 @@ export class RecordService {
logger.info("【录音服务RecordService】 == 结束接待! ", "RecordService"); logger.info("【录音服务RecordService】 == 结束接待! ", "RecordService");
this.stop(); this.stop();
try { try {
if (this.record != null) { if (this.record !== null) {
await this.saveAndClearRecord(isNotSave); await this.saveAndClearRecord(isNotSave);
} else { } else {
logger.warn("【录音服务RecordService】 == 结束接待时 record 为空", "RecordService"); logger.warn("【录音服务RecordService】 == 结束接待时 record 为空", "RecordService");
...@@ -331,18 +331,13 @@ export class RecordService { ...@@ -331,18 +331,13 @@ export class RecordService {
updateBusinessData(type: string, data: any | null) { updateBusinessData(type: string, data: any | null) {
if (!this.isReceptioning()) return; if (!this.isReceptioning()) return;
// 委托给 Handler 处理 // 委托给 Handler 处理,传入 recordId 以便策略自行决定缓存还是持久化
const result = this.businessHandler.handle(type, data); const result = this.businessHandler.handle(type, data, this.record?.currentRecord?.id ?? "");
// 处理结果:可能是 DB 更新,也可能是缓存操作 // 如果策略返回 null,说明已经由策略自行处理(如缓存)或无需处理
if (result === null) return; if (result === null) return;
if (result._isCache === true) {
const list = result.value as UTSJSONObject[]; // 如果策略返回了数据对象,则交由 Service 进行预记录持久化 (updatePreRecords)
if (this.record !== null) { this.record?.updatePreRecords(result);
this.record.cacheMaterialPoints(list); // 这里其实也可以泛化,比如 cache(key, val)
}
} else {
this.record?.updatePreRecords(result);
}
} }
} }
......
import { storage } from "../../../utils/storage.uts"; import { storage } from "../../../utils/storage.uts";
import RecordCache from "../RecordCache.uts";
import { BusinessDataType } from "../types/handler.uts"; import { BusinessDataType } from "../types/handler.uts";
import { IRecorderStrategy } from "../types/strategy.uts"; import { IRecorderStrategy } from "../types/strategy.uts";
...@@ -8,6 +9,50 @@ import { IRecorderStrategy } from "../types/strategy.uts"; ...@@ -8,6 +9,50 @@ import { IRecorderStrategy } from "../types/strategy.uts";
*/ */
export class DefaultRecorderStrategy implements IRecorderStrategy { export class DefaultRecorderStrategy implements IRecorderStrategy {
// 缓存配置:Key前缀 -> 目标字段名
private cacheConfig: Map<string, string> = new Map([
["MATERIAL_POINTS_", "receptionCustomerMaterialPointList"]
]);
/**
* 实现缓存写入逻辑
*/
cacheBusinessData(recordId: string, type: string, data: any): void {
// 映射 type 到 keyPrefix
let keyPrefix = "";
if (type == "MATERIAL_POINTS") {
keyPrefix = "MATERIAL_POINTS_";
}
// 如果有更多类型,可以在这里扩展,或者直接传入 keyPrefix
if (keyPrefix != "") {
RecordCache.set(recordId, keyPrefix, data);
}
}
/**
* 实现缓存清理逻辑
*/
clearBusinessCache(recordId: string): void {
const keyList: string[] = [];
this.cacheConfig.forEach((_, key) => {
keyList.push(key);
});
RecordCache.clearAll(recordId, keyList);
}
/**
* 实现缓存消费逻辑
*/
async consumeBusinessCache(recordId: string, currentRecord: UTSJSONObject): Promise<UTSJSONObject> {
// 调用通用缓存管理器的消费方法,传入当前策略的配置
const restored = await RecordCache.consumeAll(recordId, this.cacheConfig);
// 合并到当前记录
const result = Object.assign({}, currentRecord, restored);
return result;
}
getBussinessType(sceneType: any | null): number { getBussinessType(sceneType: any | null): number {
return sceneType === 0 ? 1 : 2; // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改 return sceneType === 0 ? 1 : 2; // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
} }
...@@ -32,7 +77,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy { ...@@ -32,7 +77,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
const sceneType = obj.get("sceneType"); const sceneType = obj.get("sceneType");
const dynamicAttrs = { const dynamicAttrs = {
bussinessType: this.getBussinessType(sceneType) bussinessType: this.getBussinessType(sceneType)
}; };
return dynamicAttrs; return dynamicAttrs;
} catch (error) { } catch (error) {
...@@ -83,7 +128,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy { ...@@ -83,7 +128,7 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
]; ];
} }
handle(type: string, data: any | null): null | UTSJSONObject { handle(type: string, data: any | null, recordId: string): null | UTSJSONObject {
switch (type) { switch (type) {
case BusinessDataType.BOOK as string: { case BusinessDataType.BOOK as string: {
return this.processBookList(data as UTSJSONObject[]); return this.processBookList(data as UTSJSONObject[]);
...@@ -92,7 +137,19 @@ export class DefaultRecorderStrategy implements IRecorderStrategy { ...@@ -92,7 +137,19 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
return this.processCustomerInfo(data as null | UTSJSONObject); return this.processCustomerInfo(data as null | UTSJSONObject);
} }
case BusinessDataType.MATERIAL as string: { case BusinessDataType.MATERIAL as string: {
return this.processMaterialPoints(data as UTSJSONObject[]); // 直接在这里进行缓存写入
const result = this.processMaterialPoints(data as UTSJSONObject[]);
// 检查是否需要缓存
if (result.getBoolean("_isCache") === true) {
const key = result.getString("key");
const val = result.get("value");
if (key !== null && val !== null) {
this.cacheBusinessData(recordId, key, val);
}
// 返回 null,表示 Service 不需要再做任何处理(包括更新 DB)
return null;
}
return result;
} }
case BusinessDataType.STATUS as string: { case BusinessDataType.STATUS as string: {
return this.processReceptionStatus(data as string); return this.processReceptionStatus(data as string);
......
...@@ -23,9 +23,10 @@ export interface IBusinessDataHandler { ...@@ -23,9 +23,10 @@ export interface IBusinessDataHandler {
* 通用数据处理方法 * 通用数据处理方法
* @param type 数据类型标识 (建议使用 BusinessDataType 枚举值) * @param type 数据类型标识 (建议使用 BusinessDataType 枚举值)
* @param data 原始业务数据 * @param data 原始业务数据
* @param recordId 当前记录ID
* @returns 处理后的数据 (用于更新到数据库或缓存) * @returns 处理后的数据 (用于更新到数据库或缓存)
* 返回 null 表示无需处理或忽略 * 返回 null 表示无需处理或忽略
* 返回带有 _isCache: true 的对象表示缓存操作 * 返回带有 _isCache: true 的对象表示缓存操作
*/ */
handle(type: string, data: any | null): null | UTSJSONObject handle(type: string, data: any | null, recordId: string): null | UTSJSONObject
} }
import { IBusinessDataHandler } from './handler' import { IBusinessDataHandler } from "./handler";
/** /**
* 录音业务策略接口 * 录音业务策略接口
...@@ -31,4 +31,26 @@ export interface IRecorderStrategy extends IBusinessDataHandler { ...@@ -31,4 +31,26 @@ export interface IRecorderStrategy extends IBusinessDataHandler {
* 这些数据通常在初始化时可能还未就绪,或者会动态变化 * 这些数据通常在初始化时可能还未就绪,或者会动态变化
*/ */
getDynamicAttributes(): UTSJSONObject getDynamicAttributes(): UTSJSONObject
/**
* 业务缓存处理:将业务数据存入缓存
* @param recordId 记录ID
* @param type 缓存子类型 (由 Handler 返回的 key)
* @param data 数据载荷
*/
cacheBusinessData(recordId: string, type: string, data: any): void
/**
* 业务缓存消费:从缓存中恢复所有业务数据并合并到记录中
* @param recordId 记录ID
* @param currentRecord 当前的记录对象(用于合并)
* @returns 包含恢复后数据的完整对象
*/
consumeBusinessCache(recordId: string, currentRecord: UTSJSONObject): Promise<UTSJSONObject>
/**
* 清理该记录的所有业务缓存
* @param recordId 记录ID
*/
clearBusinessCache(recordId: string): void
} }
...@@ -40,7 +40,7 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy { ...@@ -40,7 +40,7 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy {
}; };
const policyBase64 = this.getPolicyBase64(policyObj); const policyBase64 = this.getPolicyBase64(policyObj);
// 增加 null 检查 // 增加 null 检查
if (accessKeySecret == null) { if (accessKeySecret === null) {
console.error("[AliUniUploadStrategy] accessKeySecret is null"); console.error("[AliUniUploadStrategy] accessKeySecret is null");
throw new Error("accessKeySecret is null"); throw new Error("accessKeySecret is null");
} }
...@@ -62,7 +62,7 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy { ...@@ -62,7 +62,7 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy {
name: "file", name: "file",
formData: formData as UTSJSONObject, formData: formData as UTSJSONObject,
success: (res) => { success: (res) => {
if (res.statusCode == 200 || res.statusCode == 204) { if (res.statusCode === 200 || res.statusCode === 204) {
logger.info(`[AliUniUploadStrategy] 上传成功: ${objectKey}`, "FileUploadService"); logger.info(`[AliUniUploadStrategy] 上传成功: ${objectKey}`, "FileUploadService");
const url = `${host}/${objectKey}`; const url = `${host}/${objectKey}`;
...@@ -92,7 +92,7 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy { ...@@ -92,7 +92,7 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy {
*/ */
getPolicyBase64(policyObj: any): string { getPolicyBase64(policyObj: any): string {
const policyStr = JSON.stringify(policyObj); const policyStr = JSON.stringify(policyObj);
if (policyStr == null) return ""; if (policyStr === null) return "";
return base64Encode(policyStr).replaceAll("\n", ""); return base64Encode(policyStr).replaceAll("\n", "");
} }
......
/* /*
* @Descripttion: 通用文件上传服务 (策略模式) * @Description: 通用文件上传服务 (策略模式)
* @version: 1.1.0 * @version: 1.1.0
* @Author: limin * @Author: limin
* @Date: 2026-03-01 * @Date: 2026-03-01
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\uploader\FileUploadService.uts * @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\uploader\FileUploadService.uts
*/ */
import { logger } from "../logger/index.uts"; import { logger } from "../logger/index.uts";
...@@ -27,10 +27,10 @@ class FileUploadService { ...@@ -27,10 +27,10 @@ class FileUploadService {
} }
static getInstance(): FileUploadService { static getInstance(): FileUploadService {
if (FileUploadService.instance == null) { if (FileUploadService.instance === null) {
FileUploadService.instance = new FileUploadService(); FileUploadService.instance = new FileUploadService();
} }
return FileUploadService.instance!; return FileUploadService.instance;
} }
/** /**
...@@ -38,17 +38,25 @@ class FileUploadService { ...@@ -38,17 +38,25 @@ class FileUploadService {
* @param type 策略类型 * @param type 策略类型
*/ */
setStrategy(type: UploadStrategyType) { setStrategy(type: UploadStrategyType) {
if (type == UploadStrategyType.ALI_OSS) { switch (type) {
this.strategy = new AliOSSUploadStrategy(); case UploadStrategyType.ALI_OSS: {
logger.info(`[FileUploadService] 切换策略为: AliOSS (Native SDK)`, "FileUploadService"); this.strategy = new AliOSSUploadStrategy();
} else if (type == UploadStrategyType.UNI_UPLOAD) { logger.info(`[FileUploadService] 切换策略为: AliOSS (Native SDK)`, "FileUploadService");
this.strategy = new UniUploadStrategy(); break;
logger.info(`[FileUploadService] 切换策略为: uni.uploadFile (Generic)`, "FileUploadService"); }
} else if (type == UploadStrategyType.ALI_UNI) { case UploadStrategyType.ALI_UNI: {
this.strategy = new AliUniUploadStrategy(); this.strategy = new AliUniUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: AliUni (uni.uploadFile -> OSS)`, "FileUploadService"); logger.info(`[FileUploadService] 切换策略为: AliUni (uni.uploadFile -> OSS)`, "FileUploadService");
} else { break;
logger.warn(`[FileUploadService] 未知策略: ${type}, 保持当前策略`, "FileUploadService"); }
case UploadStrategyType.UNI_UPLOAD: {
this.strategy = new UniUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: uni.uploadFile (Generic)`, "FileUploadService");
break;
}
default: {
logger.warn(`[FileUploadService] 未知策略: ${type}, 保持当前策略`, "FileUploadService");
}
} }
} }
......
...@@ -7,12 +7,12 @@ import { IUploadStrategy } from "./IUploadStrategy.uts"; ...@@ -7,12 +7,12 @@ import { IUploadStrategy } from "./IUploadStrategy.uts";
export class UniUploadStrategy implements IUploadStrategy { export class UniUploadStrategy implements IUploadStrategy {
async upload(options: UTSJSONObject): Promise<UTSJSONObject> { async upload(options: UTSJSONObject): Promise<UTSJSONObject> {
const filePath = options.getString("filePath"); const filePath = options.getString("filePath");
if (filePath == null || filePath == "") { if (filePath === null || filePath === "") {
throw new Error("filePath is required"); throw new Error("filePath is required");
} }
const uploadUrl = options.getString("uploadUrl"); const uploadUrl = options.getString("uploadUrl");
if (uploadUrl == null || uploadUrl == "") { if (uploadUrl === null || uploadUrl === "") {
throw new Error("uploadUrl is required for UniUploadStrategy"); throw new Error("uploadUrl is required for UniUploadStrategy");
} }
......
...@@ -13,7 +13,7 @@ export function isArray(value: any): boolean { ...@@ -13,7 +13,7 @@ export function isArray(value: any): boolean {
* @example isObject([]) // false * @example isObject([]) // false
*/ */
export function isObject(value: any): boolean { export function isObject(value: any): boolean {
return typeof value == "object" && !Array.isArray(value) && !isNull(value); return typeof value === "object" && !Array.isArray(value) && !isNull(value);
} }
/** /**
...@@ -22,7 +22,7 @@ export function isObject(value: any): boolean { ...@@ -22,7 +22,7 @@ export function isObject(value: any): boolean {
* @example isString(123) // false * @example isString(123) // false
*/ */
export function isString(value: any): boolean { export function isString(value: any): boolean {
return typeof value == "string"; return typeof value === "string";
} }
/** /**
...@@ -31,7 +31,7 @@ export function isString(value: any): boolean { ...@@ -31,7 +31,7 @@ export function isString(value: any): boolean {
* @example isNumber('123') // false * @example isNumber('123') // false
*/ */
export function isNumber(value: any): boolean { export function isNumber(value: any): boolean {
return typeof value == "number" && !isNaN(value); return typeof value === "number" && !isNaN(value);
} }
/** /**
...@@ -40,7 +40,7 @@ export function isNumber(value: any): boolean { ...@@ -40,7 +40,7 @@ export function isNumber(value: any): boolean {
* @example isBoolean(1) // false * @example isBoolean(1) // false
*/ */
export function isBoolean(value: any): boolean { export function isBoolean(value: any): boolean {
return typeof value == "boolean"; return typeof value === "boolean";
} }
/** /**
...@@ -49,7 +49,7 @@ export function isBoolean(value: any): boolean { ...@@ -49,7 +49,7 @@ export function isBoolean(value: any): boolean {
* @example isFunction({}) // false * @example isFunction({}) // false
*/ */
export function isFunction(value: any): boolean { export function isFunction(value: any): boolean {
return typeof value == "function"; return typeof value === "function";
} }
/** /**
...@@ -75,7 +75,7 @@ export function isNull(value?: any | null): boolean { ...@@ -75,7 +75,7 @@ export function isNull(value?: any | null): boolean {
*/ */
export function isEmpty(value: any): boolean { export function isEmpty(value: any): boolean {
if (isArray(value)) { if (isArray(value)) {
return (value as any[]).length == 0; return (value as any[]).length === 0;
} }
if (isString(value)) { if (isString(value)) {
...@@ -83,7 +83,7 @@ export function isEmpty(value: any): boolean { ...@@ -83,7 +83,7 @@ export function isEmpty(value: any): boolean {
} }
if (isObject(value)) { if (isObject(value)) {
return keys(value).length == 0; return keys(value).length === 0;
} }
return false; return false;
...@@ -93,19 +93,19 @@ export function isEmpty(value: any): boolean { ...@@ -93,19 +93,19 @@ export function isEmpty(value: any): boolean {
* 返回对象的所有键名 * 返回对象的所有键名
* @example keys({a: 1, b: 2}) // ['a', 'b'] * @example keys({a: 1, b: 2}) // ['a', 'b']
*/ */
export const nullValues = [null, ""] export const nullValues = [null, ""];
/** /**
* 格式化日期时间 * 格式化日期时间
*/ */
export function convertDateTimeFormat(date: Date, separator: string): string { export function convertDateTimeFormat(date: Date, separator: string): string {
const year = date.getFullYear() const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0') const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, '0') const day = date.getDate().toString().padStart(2, "0");
const hours = date.getHours().toString().padStart(2, '0') const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, '0') const minutes = date.getMinutes().toString().padStart(2, "0");
const seconds = date.getSeconds().toString().padStart(2, '0') const seconds = date.getSeconds().toString().padStart(2, "0");
return `${year}${separator}${month}${separator}${day} ${hours}:${minutes}:${seconds}` return `${year}${separator}${month}${separator}${day} ${hours}:${minutes}:${seconds}`;
} }
/** /**
...@@ -138,7 +138,7 @@ export function getUUID(): string { ...@@ -138,7 +138,7 @@ export function getUUID(): string {
* @example first([1, 2, 3]) // 1 * @example first([1, 2, 3]) // 1
* @example first([]) // null * @example first([]) // null
*/ */
export function first<T>(array: T[]): T | null { export function first<T>(array: T[]): null | T {
return isArray(array) && array.length > 0 ? array[0] : null; return isArray(array) && array.length > 0 ? array[0] : null;
} }
...@@ -147,7 +147,7 @@ export function first<T>(array: T[]): T | null { ...@@ -147,7 +147,7 @@ export function first<T>(array: T[]): T | null {
* @example last([1, 2, 3]) // 3 * @example last([1, 2, 3]) // 3
* @example last([]) // null * @example last([]) // null
*/ */
export function last<T>(array: T[]): T | null { export function last<T>(array: T[]): null | T {
return isArray(array) && array.length > 0 ? array[array.length - 1] : null; return isArray(array) && array.length > 0 ? array[array.length - 1] : null;
} }
...@@ -214,8 +214,8 @@ export function map<T, U>(array: T[], iteratee: (item: T, index: number) => U): ...@@ -214,8 +214,8 @@ export function map<T, U>(array: T[], iteratee: (item: T, index: number) => U):
if (!isArray(array)) return result; if (!isArray(array)) return result;
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
result.push(iteratee(array[i], i)); result.push(iteratee(element, i));
} }
return result; return result;
...@@ -233,8 +233,8 @@ export function reduce<T, U>( ...@@ -233,8 +233,8 @@ export function reduce<T, U>(
if (!isArray(array)) return initialValue; if (!isArray(array)) return initialValue;
let accumulator: U = initialValue; let accumulator: U = initialValue;
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
accumulator = iteratee(accumulator, array[i], i); accumulator = iteratee(accumulator, element, i);
} }
return accumulator; return accumulator;
...@@ -247,8 +247,8 @@ export function reduce<T, U>( ...@@ -247,8 +247,8 @@ export function reduce<T, U>(
export function every<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean { export function every<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return true; if (!isArray(array)) return true;
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
if (!predicate(array[i], i)) { if (!predicate(element, i)) {
return false; return false;
} }
} }
...@@ -263,8 +263,8 @@ export function every<T>(array: T[], predicate: (value: T, index: number) => boo ...@@ -263,8 +263,8 @@ export function every<T>(array: T[], predicate: (value: T, index: number) => boo
export function some<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean { export function some<T>(array: T[], predicate: (value: T, index: number) => boolean): boolean {
if (!isArray(array)) return false; if (!isArray(array)) return false;
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
if (predicate(array[i], i)) { if (predicate(element, i)) {
return true; return true;
} }
} }
...@@ -282,8 +282,7 @@ export function uniq<T>(array: T[]): T[] { ...@@ -282,8 +282,7 @@ export function uniq<T>(array: T[]): T[] {
const result: T[] = []; const result: T[] = [];
const seen = new Map<T, boolean>(); const seen = new Map<T, boolean>();
for (let i = 0; i < array.length; i++) { for (const item of array) {
const item = array[i];
const key = item; const key = item;
if (!seen.has(item)) { if (!seen.has(item)) {
seen.set(key, true); seen.set(key, true);
...@@ -303,8 +302,7 @@ export function flatten(array: any[]): any[] { ...@@ -303,8 +302,7 @@ export function flatten(array: any[]): any[] {
const result: any[] = []; const result: any[] = [];
for (let i = 0; i < array.length; i++) { for (const item of array) {
const item = array[i];
if (isArray(item)) { if (isArray(item)) {
result.push(...(item as any[])); result.push(...(item as any[]));
} else { } else {
...@@ -324,8 +322,7 @@ export function flattenDeep(array: any[]): any[] { ...@@ -324,8 +322,7 @@ export function flattenDeep(array: any[]): any[] {
const result: any[] = []; const result: any[] = [];
for (let i = 0; i < array.length; i++) { for (const item of array) {
const item = array[i];
if (isArray(item)) { if (isArray(item)) {
result.push(...flattenDeep(item as any[])); result.push(...flattenDeep(item as any[]));
} else { } else {
...@@ -345,11 +342,11 @@ export function sort<T>(array: T[], order: "asc" | "desc" = "asc"): T[] { ...@@ -345,11 +342,11 @@ export function sort<T>(array: T[], order: "asc" | "desc" = "asc"): T[] {
const result = [...array]; const result = [...array];
return result.sort((a, b) => { return result.sort((a, b) => {
if (typeof a == "number" && typeof b == "number") { if (typeof a === "number" && typeof b === "number") {
return order == "asc" ? a - b : b - a; return order == "asc" ? a - b : b - a;
} }
if (typeof a == "string" && typeof b == "string") { if (typeof a === "string" && typeof b === "string") {
return order == "asc" ? a.localeCompare(b) : b.localeCompare(a); return order == "asc" ? a.localeCompare(b) : b.localeCompare(a);
} }
...@@ -389,15 +386,14 @@ export function groupBy<T>(array: T[], key: string) { ...@@ -389,15 +386,14 @@ export function groupBy<T>(array: T[], key: string) {
const result = {}; const result = {};
for (let i = 0; i < array.length; i++) { for (const item of array) {
const item = array[i];
let value = get(item as any, key)!; let value = get(item as any, key)!;
if (typeof value == "number") { if (typeof value === "number") {
value = value.toString(); value = value.toString();
} }
if (typeof value == "string") { if (typeof value === "string") {
if (!isArray(result[value])) { if (!isArray(result[value])) {
result[value] = new Array<T>(); result[value] = new Array<T>();
} }
...@@ -423,7 +419,7 @@ export function assign(...items: any[]) { ...@@ -423,7 +419,7 @@ export function assign(...items: any[]) {
* @example nth([1, 2, 3], 1) // 2 * @example nth([1, 2, 3], 1) // 2
* @example nth([1, 2, 3], -1) // 3 * @example nth([1, 2, 3], -1) // 3
*/ */
export function nth<T>(array: T[], index: number): T | null { export function nth<T>(array: T[], index: number): null | T {
if (index >= 0) { if (index >= 0) {
return array[index]; return array[index];
} }
...@@ -450,9 +446,9 @@ export function remove<T>(array: T[], predicate: (value: T, index: number) => bo ...@@ -450,9 +446,9 @@ export function remove<T>(array: T[], predicate: (value: T, index: number) => bo
const result: T[] = []; const result: T[] = [];
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
if (!predicate(array[i], i)) { if (!predicate(element, i)) {
result.push(array[i]); result.push(element);
} }
} }
...@@ -467,9 +463,9 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi ...@@ -467,9 +463,9 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi
if (isArray(data)) { if (isArray(data)) {
const array = data as T[]; const array = data as T[];
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
if (array[i] != null) { if (element != null) {
iteratee(array[i], i); iteratee(element, i);
} }
} }
} }
...@@ -479,12 +475,12 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi ...@@ -479,12 +475,12 @@ export function forEach<T>(data: T[], iteratee: (value: T, index: number) => voi
* 查找数组中第一个满足条件的元素 * 查找数组中第一个满足条件的元素
* @example find([1, 2, 3, 4], x => x > 2) // 3 * @example find([1, 2, 3, 4], x => x > 2) // 3
*/ */
export function find<T>(array: T[], predicate: (value: T, index: number) => boolean): T | null { export function find<T>(array: T[], predicate: (value: T, index: number) => boolean): null | T {
if (!isArray(array)) return null; if (!isArray(array)) return null;
for (let i = 0; i < array.length; i++) { for (const [i, element] of array.entries()) {
if (predicate(array[i], i)) { if (predicate(element, i)) {
return array[i]; return element;
} }
} }
return null; return null;
...@@ -497,8 +493,7 @@ export function find<T>(array: T[], predicate: (value: T, index: number) => bool ...@@ -497,8 +493,7 @@ export function find<T>(array: T[], predicate: (value: T, index: number) => bool
export function forInObject(data: any, iteratee: (value: any, key: string) => void): void { export function forInObject(data: any, iteratee: (value: any, key: string) => void): void {
if (isObject(data)) { if (isObject(data)) {
const objKeys = keys(data); const objKeys = keys(data);
for (let i = 0; i < objKeys.length; i++) { for (const key of objKeys) {
const key = objKeys[i];
iteratee(get(data, key)!, key); iteratee(get(data, key)!, key);
} }
} }
...@@ -595,9 +590,9 @@ export function random(min: number, max: number): number { ...@@ -595,9 +590,9 @@ export function random(min: number, max: number): number {
*/ */
export function base64ToBlob(data: string, type: string = "image/jpeg"): Blob { export function base64ToBlob(data: string, type: string = "image/jpeg"): Blob {
// #ifdef H5 // #ifdef H5
let bytes = window.atob(data.split(",")[1]); const bytes = window.atob(data.split(",")[1]);
let ab = new ArrayBuffer(bytes.length); const ab = new ArrayBuffer(bytes.length);
let ia = new Uint8Array(ab); const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) { for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i); ia[i] = bytes.charCodeAt(i);
} }
...@@ -629,17 +624,33 @@ export function isEqual(a: any, b: any): boolean { ...@@ -629,17 +624,33 @@ export function isEqual(a: any, b: any): boolean {
* @returns 替换后的字符串 * @returns 替换后的字符串
*/ */
export function replaceAll(text: string, find: string, replace: string): string { export function replaceAll(text: string, find: string, replace: string): string {
if (text.indexOf(find) == -1) { if (text.indexOf(find) == -1) {
return text return text;
} }
const parts = text.split(find) const parts = text.split(find);
let res = "" let res = "";
for (let i = 0; i < parts.length; i++) { for (let i = 0; i < parts.length; i++) {
const part = parts[i] const part = parts[i];
res = res + part res = res + part;
if (i < parts.length - 1) { if (i < parts.length - 1) {
res = res + replace res = res + replace;
} }
} }
return res return res;
}
/**
* 深拷贝对象
* @param obj 要拷贝的对象
* @returns 拷贝后的对象
*/
export function deepClone<T>(obj: any): null | T {
// UTS 要求返回类型明确包含 null
if (obj == null) {
return null;
}
if (typeof obj === "object") {
return JSON.parse<T>(JSON.stringify(obj));
}
return obj as T;
} }
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
"language": "en,en-US", "language": "en,en-US",
"allowCompoundWords": true, "allowCompoundWords": true,
"words": [ "words": [
"wxml",
"acmr", "acmr",
"antd", "antd",
"antdv", "antdv",
...@@ -18,10 +17,13 @@ ...@@ -18,10 +17,13 @@
"esno", "esno",
"etag", "etag",
"execa", "execa",
"hmac",
"iconify", "iconify",
"iconoir", "iconoir",
"intlify", "intlify",
"limin",
"lockb", "lockb",
"lsaccess",
"lucide", "lucide",
"minh", "minh",
"minw", "minw",
...@@ -46,6 +48,7 @@ ...@@ -46,6 +48,7 @@
"uicons", "uicons",
"unplugin", "unplugin",
"unref", "unref",
"UTSJSONObject",
"venus", "venus",
"venusjs", "venusjs",
"vite", "vite",
...@@ -53,6 +56,7 @@ ...@@ -53,6 +56,7 @@
"vitepress", "vitepress",
"vnode", "vnode",
"vueuse", "vueuse",
"wxml",
"yxxx" "yxxx"
], ],
"ignorePaths": [ "ignorePaths": [
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!