Commit d053d859 by liimin

refactor(上传服务): 重构OSS配置管理并统一代码风格

- 新增 oss.config.uts 集中管理OSS默认配置
- 重构 AliOSSBaseStrategy 使用统一配置并确保token字段完整性
- 优化类型定义顺序和代码格式,统一使用严格相等判断
- 清理无用代码和注释,调整方法顺序提升可读性
- 修复潜在的空值访问问题和类型定义不一致
1 parent c492c30e
/**
* 公共 API(从 gl_tape/api/module/common.js 迁移)
*/
import http from '@/api/request/http.uts'
import http from "@/api/request/http.uts";
/** 获取交付人员列表 */
export function getEmployeeList(data: UTSJSONObject): Promise<any> {
return http.post({
'method': 'dj.api.smartcarlife.employee.getByMerchantId',
'projectName': 'boutique',
'sceneList': [1],
"method": "dj.api.smartcarlife.employee.getByMerchantId",
"projectName": "boutique",
"sceneList": [1],
...data
} as UTSJSONObject)
} as UTSJSONObject);
}
export const OSS_CONFIG = {
defaultBucket: "glsk-oss",
defaultRegion: "oss-cn-shenzhen"
} as UTSJSONObject;
......@@ -7,8 +7,8 @@ import { logger } from "../logger/index.uts";
* @Author: limin
* @Date: 2024-11-22 08:18:23
* @LastEditors: limin
* @LastEditTime: 2026-01-13 19:02:14
* @FilePath: \gl_tape\utils\recordManager\DBBase.uts
* @LastEditTime: 2026-03-06 12:35:23
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\db\DBBase.uts
*/
import SQLite from "./sqlite.uts";
......@@ -17,7 +17,7 @@ import SQLite from "./sqlite.uts";
* 用于管理记录列表
*/
export default class DBBase implements IDBBase {
db: null | SQLite = null;
db: SQLite;
db_description = "zyzs db";
db_name = "zyzs";
db_size = 50 * 1024 * 1024;
......@@ -42,7 +42,7 @@ export default class DBBase implements IDBBase {
* @returns {Array} - 包含新记录的更新后的记录列表
*/
async addRecord(record: UTSJSONObject): Promise<void> {
await this.db!.insert(this.table_name, record);
await this.db.insert(this.table_name, record);
}
/**
......@@ -78,11 +78,11 @@ export default class DBBase implements IDBBase {
// 让我们先暂时注释掉或抛出未实现,或者传入 dummy where。
// 或者直接调用 this.db!.executeSql(`DELETE FROM ${this.table_name}`),虽然是 private 或者是 public?
// sqlite.uts 中 executeSql 是 public 的。
await this.db!.executeSql(`DELETE FROM ${this.table_name}`);
await this.db.executeSql(`DELETE FROM ${this.table_name}`);
}
async drop() {
this.db!.drop(this.table_name);
this.db.drop(this.table_name);
}
/**
......@@ -94,7 +94,7 @@ export default class DBBase implements IDBBase {
*/
async getRecordById(id: any): Promise<null | UTSJSONObject> {
const where = { id };
const records = await this.db!.select(this.table_name, where, null);
const records = await this.db.select(this.table_name, where, null);
// records 是 any[],需要断言
if (records.length > 0) {
return records[0] as UTSJSONObject;
......@@ -108,7 +108,7 @@ export default class DBBase implements IDBBase {
* @returns {Array} - 从 storageApi 获取的记录列表
*/
async getRecords(): Promise<any[]> {
return this.db!.select(this.table_name, null, null);
return this.db.select(this.table_name, null, null);
}
/**
......@@ -117,7 +117,7 @@ export default class DBBase implements IDBBase {
* @returns {Array} - 记录列表
*/
async getRecordsByWhere(where: UTSJSONObject): Promise<any[]> {
return this.db!.select(this.table_name, where, null);
return this.db.select(this.table_name, where, null);
}
async init(): Promise<boolean> {
......@@ -126,16 +126,16 @@ export default class DBBase implements IDBBase {
// 移除 isOpen 检查,直接调用 init(),因为 SQLite.init 内部已经处理了幂等性
// const isOpen = this.db!.isOpen()
// if (!isOpen) {
await this.db!.init();
await this.db.init();
// }
if (this.table_name == null) {
throw new Error("DBBase: table_name is null");
}
const isTableExists = await this.db!.isTableExists(this.table_name);
const isTableExists = await this.db.isTableExists(this.table_name);
logger.warn(`数据库是否存在isTableExists: ${isTableExists}`, "DBBase");
if (!isTableExists) {
await this.db!.createTable(this.table_name, this.table_columns);
await this.db.createTable(this.table_name, this.table_columns);
this.tableCreated = true;
} else {
logger.warn(`[${this.table_name}] 表已存在, 将检查并更新列`, "DBBase");
......@@ -148,11 +148,9 @@ export default class DBBase implements IDBBase {
}
async isOpen(): Promise<boolean> {
return this.db!.isOpen();
return this.db.isOpen();
}
async openDB() {}
/**
* 移除一个ID对应的记录
*
......@@ -161,7 +159,7 @@ export default class DBBase implements IDBBase {
*/
async removeRecord(id: any): Promise<any> {
const where = { id };
return this.db!.delete(this.table_name, where);
return this.db.delete(this.table_name, where);
}
// async isTableExists(): Promise<boolean> {
......@@ -197,8 +195,8 @@ export default class DBBase implements IDBBase {
let whereCondition = where;
const dataToUpdate = JSON.parse(JSON.stringify(setData)) as UTSJSONObject; // 深拷贝以避免修改原对象
if (whereCondition == null) {
if (dataToUpdate.id != null) {
if (whereCondition === null) {
if (dataToUpdate.id !== null) {
whereCondition = { id: dataToUpdate.id };
// 从更新数据中移除 id,通常 id 是主键不更新
// dataToUpdate.delete('id') // UTS Map delete? UTSJSONObject 没有 delete 方法?
......@@ -212,6 +210,6 @@ export default class DBBase implements IDBBase {
}
}
return this.db!.update(this.table_name, dataToUpdate, whereCondition!);
return this.db.update(this.table_name, dataToUpdate, whereCondition);
}
}
......@@ -4,9 +4,9 @@
// import * as Sentry from "sentry-uts";
export type UserInfo = {
extra?: UTSJSONObject
id: string
name: string
extra?: UTSJSONObject
}
export type Tag = {
......@@ -15,67 +15,67 @@ export type Tag = {
}
export type RemoteLogOptions = {
msg: string
extra?: UTSJSONObject
msg: string
tag?: Tag
}
export class RemoteLog {
// private sentry: any = null;
// private sentry: any = null;
constructor(user: UserInfo) {
// this.sentry = Sentry.init({...});
// Sentry.setUser(user);
console.log("[RemoteLog] Init with user:", user);
}
constructor(user: UserInfo) {
// this.sentry = Sentry.init({...});
// Sentry.setUser(user);
console.log("[RemoteLog] Init with user:", user);
}
debug(options: RemoteLogOptions) {
this.send("debug", options);
}
debug(options: RemoteLogOptions) {
this.send("debug", options);
}
info(options: RemoteLogOptions) {
this.send("info", options);
}
error(options: RemoteLogOptions) {
this.send("error", options);
}
warn(options: RemoteLogOptions) {
this.send("warn", options);
}
info(options: RemoteLogOptions) {
this.send("info", options);
}
error(options: RemoteLogOptions) {
this.send("error", options);
}
warn(options: RemoteLogOptions) {
this.send("warn", options);
}
private send(level: string, options: RemoteLogOptions) {
// 模拟发送逻辑
// 在实际项目中,这里会调用 Sentry 的 API
private send(level: string, options: RemoteLogOptions) {
// 模拟发送逻辑
// 在实际项目中,这里会调用 Sentry 的 API
const systemInfo = uni.getSystemInfoSync();
const enhancedExtra = {
device_brand: systemInfo.deviceBrand,
device_model: systemInfo.deviceModel,
os_name: systemInfo.osName,
os_version: systemInfo.osVersion,
uni_platform: systemInfo.uniPlatform,
app_version: systemInfo.appVersion,
};
const systemInfo = uni.getSystemInfoSync();
const enhancedExtra = {
device_brand: systemInfo.deviceBrand,
device_model: systemInfo.deviceModel,
os_name: systemInfo.osName,
os_version: systemInfo.osVersion,
uni_platform: systemInfo.uniPlatform,
app_version: systemInfo.appVersion,
};
if (options.extra != null) {
// 手动合并 extra
// UTSJSONObject 无法直接遍历 keys,这里仅作占位
// 如果需要合并,建议在调用处直接传递合并后的对象
}
if (options.extra != null) {
// 手动合并 extra
// UTSJSONObject 无法直接遍历 keys,这里仅作占位
// 如果需要合并,建议在调用处直接传递合并后的对象
}
console.log(`[RemoteLog] Sending [${level}]`, {
msg: options.msg,
tag: options.tag,
extra: enhancedExtra,
user_extra: options.extra
});
console.log(`[RemoteLog] Sending [${level}]`, {
msg: options.msg,
tag: options.tag,
extra: enhancedExtra,
user_extra: options.extra
});
// if (options.msg instanceof Error) {
// Sentry.captureException(options.msg);
// } else {
// Sentry.captureMessage(String(options.msg), level);
// }
}
// if (options.msg instanceof Error) {
// Sentry.captureException(options.msg);
// } else {
// Sentry.captureMessage(String(options.msg), level);
// }
}
}
import { logger as uniLogger, LogLevel } from '@/uni_modules/uni-logger/index.uts';
import { LogLevel, logger as uniLogger } from "@/uni_modules/uni-logger/index.uts";
import { RemoteLog, RemoteLogOptions, UserInfo } from './RemoteLog';
import { RemoteLog, RemoteLogOptions, UserInfo } from "./RemoteLog";
export class Logger {
private static instance: Logger | null = null;
private remote: RemoteLog | null = null;
private user: UserInfo | null = null;
private static instance: Logger | null = null;
private remote: null | RemoteLog = null;
private user: null | UserInfo = null;
private constructor() {
// 设置 uni-logger 的远程处理器钩子
uniLogger.setRemoteHandler((level: LogLevel, tag: string, msg: string) => {
// 这里可以过滤某些不需要上报的日志,或者只上报 error 级别
if (this.remote != null) {
const options = {
msg: msg,
tag: { key: "module", value: tag }
} as RemoteLogOptions;
private constructor() {
// 设置 uni-logger 的远程处理器钩子
uniLogger.setRemoteHandler((level: LogLevel, tag: string, msg: string) => {
// 这里可以过滤某些不需要上报的日志,或者只上报 error 级别
if (this.remote != null) {
const options = {
msg,
tag: { key: "module", value: tag }
} as RemoteLogOptions;
switch (level) {
case "debug": this.remote!.debug(options); break;
case "info": this.remote!.info(options); break;
case "warn": this.remote!.warn(options); break;
case "error": this.remote!.error(options); break;
}
}
});
}
switch (level) {
case "debug": { this.remote.debug(options); break;
}
case "error": { this.remote.error(options); break;
}
case "info": { this.remote.info(options); break;
}
case "warn": { this.remote.warn(options); break;
}
}
}
});
}
static getInstance(): Logger {
if (Logger.instance == null) {
Logger.instance = new Logger();
}
return Logger.instance!;
}
static getInstance(): Logger {
if (Logger.instance === null) {
Logger.instance = new Logger();
}
return Logger.instance;
}
init(user: UserInfo) {
this.user = user;
this.remote = new RemoteLog(user);
uniLogger.info(`Logger initialized for user: ${user.name}`);
}
/**
/**
* 打印调试日志
* @param msg 日志内容
* @param tag 标签,默认 "App"
*/
debug(msg: any, tag: string = "App") {
uniLogger.setTag(tag);
uniLogger.debug(msg);
}
debug(msg: any, tag: string = "App") {
uniLogger.setTag(tag);
uniLogger.debug(msg);
}
/**
* 打印信息日志
/**
* 打印错误日志
* @param msg 日志内容
* @param tag 标签,默认 "App"
*/
info(msg: any, tag: string = "App") {
uniLogger.setTag(tag);
uniLogger.info(msg);
}
error(msg: any, tag: string = "App") {
uniLogger.setTag(tag);
uniLogger.error(msg);
}
/**
* 打印警告日志
/**
* 打印信息日志
* @param msg 日志内容
* @param tag 标签,默认 "App"
*/
warn(msg: any, tag: string = "App") {
uniLogger.setTag(tag);
uniLogger.warn(msg);
}
info(msg: any, tag: string = "App") {
uniLogger.setTag(tag);
uniLogger.info(msg);
}
/**
* 打印错误日志
init(user: UserInfo) {
this.user = user;
this.remote = new RemoteLog(user);
uniLogger.info(`Logger initialized for user: ${user.name}`);
}
/**
* 打印警告日志
* @param msg 日志内容
* @param tag 标签,默认 "App"
*/
error(msg: any, tag: string = "App") {
uniLogger.setTag(tag);
uniLogger.error(msg);
}
warn(msg: any, tag: string = "App") {
uniLogger.setTag(tag);
uniLogger.warn(msg);
}
}
export const logger = Logger.getInstance();
......@@ -6,8 +6,8 @@ import type { IDBRecord, RecordData } from "./types";
* @Author: limin
* @Date: 2025-01-02 18:34:39
* @LastEditors: limin
* @LastEditTime: 2026-03-05 19:28:54
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\recorder\DBRecord.uts
* @LastEditTime: 2026-03-06 12:40:15
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\DBRecord.uts
*/
import DBBase from "../db/DBBase.uts";
import { logger } from "../logger/index.uts";
......@@ -81,7 +81,7 @@ class DBRecord extends DBBase implements IDBRecord {
}
override async init(): Promise<boolean> {
if (this._initPromise != null) return this._initPromise!;
if (this._initPromise !== null) return this._initPromise;
this._initPromise = (async (): Promise<boolean> => {
try {
......@@ -98,7 +98,7 @@ class DBRecord extends DBBase implements IDBRecord {
throw error;
}
})();
return this._initPromise!;
return this._initPromise;
}
setStrategy(strategy: IRecorderStrategy) {
......@@ -125,7 +125,7 @@ class DBRecord extends DBBase implements IDBRecord {
*/
private async checkAndAddColumns(): Promise<void> {
// 优化:只查询一次表结构
const columnInfo = await this.db!.selectSql(`PRAGMA table_info(${this.table_name})`);
const columnInfo = await this.db.selectSql(`PRAGMA table_info(${this.table_name})`);
// columnInfo is any[], item is UTSJSONObject
const existingColumns = columnInfo.map((col: any): string => {
const c = col as UTSJSONObject;
......@@ -152,7 +152,7 @@ class DBRecord extends DBBase implements IDBRecord {
});
if (columnsToAdd.length > 0) {
await this.db!.addColumns(this.table_name, columnsToAdd);
await this.db.addColumns(this.table_name, columnsToAdd);
const addedNames: string[] = [];
columnsToAdd.forEach(c => {
......
......@@ -4,10 +4,10 @@
* @Author: limin
* @Date: 2026-01-14 14:30:10
* @LastEditors: limin
* @LastEditTime: 2026-03-01 05:21:50
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\recorder\RecordCache.uts
* @LastEditTime: 2026-03-06 14:22:59
* @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
......@@ -15,106 +15,104 @@ type CacheConfigItem = {
}
const CACHE_CONFIG_MATERIAL_POINTS = {
keyPrefix: 'MATERIAL_POINTS_', // Storage Key 前缀
targetField: 'receptionCustomerMaterialPointList' // 对应的 Record 字段名
} as CacheConfigItem
keyPrefix: "MATERIAL_POINTS_", // Storage Key 前缀
targetField: "receptionCustomerMaterialPointList" // 对应的 Record 字段名
} as CacheConfigItem;
/**
* 记录缓存管理器
* 统一管理大字段的暂存、合并与清理
*/
class RecordCache {
/**
* 暂存数据
* @param {string} recordId - 记录ID
* @param {string} type - 缓存类型 (key of CACHE_CONFIG)
* @param {any} data - 数据
export default class RecordCache {
/**
* 清理指定记录的所有缓存
* @param {string} recordId
*/
static set(recordId: string, type: string, data: any) {
// UTS 中对象键访问需要 specific
let config: CacheConfigItem | null = null
if (type == 'MATERIAL_POINTS') {
config = CACHE_CONFIG_MATERIAL_POINTS
}
static clearAll(recordId: string) {
if (recordId == "") return;
if (recordId == "" || config == null) return
try {
uni.setStorage({
key: config.keyPrefix + recordId,
data: data,
fail: (res) => {
logger.error(`RecordCacheManager: Set ${type} failed: ${res.errMsg}`, "RecordCache")
}
})
} catch (e) {
logger.error(`RecordCacheManager: Set ${type} failed: ${e}`, "RecordCache")
}
}
const configs = [CACHE_CONFIG_MATERIAL_POINTS];
configs.forEach(config => {
try {
uni.removeStorage({
key: config.keyPrefix + recordId,
fail: (res) => {}
});
} catch {}
});
}
/**
/**
* 消费缓存:读取缓存 -> 返回数据 -> 删除缓存
* @param {Object} record - 记录对象 (仅用于获取ID)
* @returns {Object} 从缓存恢复的数据对象
* @param {object} record - 记录对象 (仅用于获取ID)
* @returns {object} 从缓存恢复的数据对象
*/
static async consumeAll(record: any): Promise<UTSJSONObject|null> {
const recordObj = record as UTSJSONObject
const recordId = recordObj.getString('id')
if (recordId == null) return {}
static async consumeAll(record: any): Promise<UTSJSONObject> {
const recordObj = record as UTSJSONObject;
const recordId = recordObj.getString("id");
if (recordId == null) return {};
const restoredData: UTSJSONObject = {}
const restoredData: UTSJSONObject = {};
// 遍历配置
// 目前只有一个,直接硬编码处理,或者用 Object.values (UTS可能不支持)
const configs = [CACHE_CONFIG_MATERIAL_POINTS]
// 遍历配置
// 目前只有一个,直接硬编码处理,或者用 Object.values (UTS可能不支持)
const configs = [CACHE_CONFIG_MATERIAL_POINTS];
for (const config of configs) {
try {
const key = config.keyPrefix + recordId
const data = await new Promise<any | null>((resolve, reject) => {
uni.getStorage({
key: key,
success: (res) => {
resolve(res.data as any | null)
},
fail: (res) => {
resolve(null as any | null)
}
})
})
for (const config of configs) {
try {
const key = config.keyPrefix + recordId;
const data = await new Promise<any | null>((resolve) => {
uni.getStorage({
key,
success: (res) => {
resolve(res.data);
},
fail: () => {
resolve(null);
}
});
});
if (data != null && data != "") {
restoredData.set(config.targetField, data)
uni.removeStorage({
key: key,
fail: (res) => {
logger.warn(`RecordCacheManager: Remove ${key} failed: ${res.errMsg}`, "RecordCache")
}
}) // 消费即焚
}
} catch (e) {
logger.warn(`RecordCacheManager: Consume ${config.keyPrefix} failed: ${e}`, "RecordCache")
}
}
return restoredData
}
if (data != null && data != "") {
restoredData[config.targetField] = data;
uni.removeStorage({
key,
fail: (res) => {
logger.warn(`RecordCacheManager: Remove ${key} failed: ${res.errMsg}`, "RecordCache");
}
}); // 消费即焚
}
} catch (error) {
logger.warn(`RecordCacheManager: Consume ${config.keyPrefix} failed: ${error}`, "RecordCache");
}
}
return restoredData;
}
/**
* 清理指定记录的所有缓存
* @param {string} recordId
/**
* 暂存数据
* @param {string} recordId - 记录ID
* @param {string} type - 缓存类型 (key of CACHE_CONFIG)
* @param {any} data - 数据
*/
static clearAll(recordId: string) {
if (recordId == "") return
static set(recordId: string, type: string, data: any) {
// UTS 中对象键访问需要 specific
let config: CacheConfigItem | null = null;
if (type == "MATERIAL_POINTS") {
config = CACHE_CONFIG_MATERIAL_POINTS;
}
const configs = [CACHE_CONFIG_MATERIAL_POINTS]
configs.forEach(config => {
try {
uni.removeStorage({
key: config.keyPrefix + recordId,
fail: (res) => {}
})
} catch (e) {}
})
}
if (recordId == "" || config == null) return;
try {
uni.setStorage({
key: config.keyPrefix + recordId,
data,
fail: (res) => {
logger.error(`RecordCacheManager: Set ${type} failed: ${res.errMsg}`, "RecordCache");
}
});
} catch (error) {
logger.error(`RecordCacheManager: Set ${type} failed: ${error}`, "RecordCache");
}
}
}
export default RecordCache
......@@ -10,8 +10,8 @@ import { replaceAll } from "../../utils/index.uts";
* @Author: limin
* @Date: 2026-01-28 20:57:12
* @LastEditors: limin
* @LastEditTime: 2026-03-05 20:30:09
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\composables\recorder\RecordSave.uts
* @LastEditTime: 2026-03-06 13:59:06
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\RecordSave.uts
*/
import Queue from "../../utils/Queue.uts";
import { logger } from "../logger/index.uts";
......@@ -69,10 +69,10 @@ class RecordSave {
}
static getInstance(): RecordSave {
if (RecordSave.sInstance == null) {
if (RecordSave.sInstance === null) {
RecordSave.sInstance = new RecordSave();
}
return RecordSave.sInstance!;
return RecordSave.sInstance;
}
/**
......@@ -143,11 +143,11 @@ class RecordSave {
return "任务正在执行中";
}
if (this.snapshot == null || this.snapshot!.size === 0) {
if (this.snapshot === null || this.snapshot.size === 0) {
await this.enQueue();
}
if (this.snapshot == null || this.snapshot!.size === 0) {
if (this.snapshot === null || this.snapshot.size === 0) {
return "队列为空";
}
return null;
......@@ -213,19 +213,13 @@ class RecordSave {
return key != "" && this._blackList.has(key);
}
// _reportParseError(msg: string, data: any, recordId: string, filePath: string) {
// const fullMsg = `【接待记录保存服务】 == ${msg}`
// logger.error(fullMsg, "RecordSave")
// this.reportError(fullMsg, data, recordId, filePath)
// }
_isTargetFile(item: UTSJSONObject, fileInfo: UTSJSONObject): boolean {
const fileName = fileInfo.fileName as string;
const clientPath = fileInfo.clientPath as string;
const itemFile = (item.file ?? item.filePath) as string;
if (!this.isLegalFile(fileName)) return !this.isLegalFile(itemFile);
return itemFile == clientPath || itemFile.endsWith(fileName);
return itemFile === clientPath || itemFile.endsWith(fileName);
}
_parseNoFileStatus(data: UTSJSONObject): UTSJSONObject {
......@@ -316,7 +310,8 @@ class RecordSave {
async _removeRecordFiles(fileArr: string[]) {
try {
while (fileArr.length > 0) {
const file = fileArr.shift()!;
const file = fileArr.shift();
if (file===null || file ==="") continue;
await this._removeFileOnClient(file);
}
logger.info(`【接待记录保存服务】 == 删除接待文件完成!`, "RecordSave");
......@@ -365,8 +360,9 @@ class RecordSave {
_scheduleNext(ms: number = 0) {
if (this.snapshot === null) return;
if (this._pumpTimer != null) {
clearTimeout(this._pumpTimer!);
const timer = this._pumpTimer;
if (timer !== null) {
clearTimeout(timer);
this._pumpTimer = null;
}
this._pumpTimer = setTimeout(
......@@ -389,7 +385,7 @@ class RecordSave {
}
// 从队列取出任务
record = this.snapshot!.dequeue();
record = this.snapshot?.dequeue();
// 执行任务
if (record != null) {
await this.beginTask(record);
......@@ -451,10 +447,10 @@ class RecordSave {
}
uni.getFileSystemManager().getFileInfo({
filePath,
success (info) {
success () {
resolve(true);
},
fail (error) {
fail () {
resolve(false);
}
});
......@@ -462,8 +458,8 @@ class RecordSave {
}
endTask() {
if (this.updateResolve != null) {
this.updateResolve!();
if (this.updateResolve !== null) {
this.updateResolve();
}
this.updateResolve = null;
this._taskStartTime = null;
......@@ -509,7 +505,7 @@ class RecordSave {
const fileUrl = (file.file ?? file.filePath);
const aFullPath = fileUrl.split("/");
const fileName = aFullPath.pop()!;
const fileName = aFullPath.pop();
const filePath = `${aFullPath.join("/") }/`;
const file2Up = deepClone(file) as UTSJSONObject;
......@@ -539,11 +535,11 @@ class RecordSave {
}
async getDbRecord(): Promise<DBRecord> {
if (this.dbRecord == null) {
if (this.dbRecord === null) {
this.dbRecord = DBRecord.getInstance();
await this.dbRecord!.init();
await this.dbRecord.init();
}
return this.dbRecord!;
return this.dbRecord;
}
async getRecordsSnapshotFlatten(): Promise<UTSJSONObject[]> {
......@@ -574,7 +570,7 @@ class RecordSave {
this.startPolling(false);
}
};
uni.onNetworkStatusChange(this._networkHandler!);
uni.onNetworkStatusChange(this._networkHandler);
logger.info("【接待记录保存服务】初始化成功", "RecordSave");
} catch (error) {
......@@ -587,8 +583,8 @@ class RecordSave {
}
off() {
if (this._networkHandler != null) {
uni.offNetworkStatusChange(this._networkHandler!);
if (this._networkHandler !== null) {
uni.offNetworkStatusChange(this._networkHandler);
this._networkHandler = null;
}
}
......@@ -612,7 +608,7 @@ class RecordSave {
// CASE 2: 直接调用 (data 是 record 对象)
const status = data.status as number;
if (data != null && (status == FileStatus.NoFile || status == FileStatus.NotExist)) {
if (data !== null && (status === FileStatus.NoFile || status === FileStatus.NotExist)) {
return this._parseNoFileStatus(data);
}
......@@ -620,32 +616,6 @@ class RecordSave {
return { error: "【接待记录保存服务】 == 未知文件状态", data, filePath };
}
async reportError(message: string, res: any, recordId: null | string, filePath: null | string) {
try {
// const dbRecord = await this.getDbRecord()
// const record = recordId != null ? await dbRecord.getRecordById(recordId) : {}
// const userInfo = (uni.getStorageSync('userInfo') as UTSJSONObject | null) ?? {}
// const customerName = record != null ? record['customerName'] : ''
// const customerPhone = record != null ? record['customerPhone'] : '' // 假设字段名
// const carType = record != null ? record['carType'] : '' // 假设字段名
// const user = (userInfo['user'] as UTSJSONObject | null) ?? {}
// const userName = user['userName']
// const now = convertDateTimeFormat(new Date(), "-")
logger.error(`${1}-${message},员工: ${1}, 客户: ${1}`, "RecordSave");
// extra info logged via msg for now
} catch (error) {
logger.error(`【接待记录保存服务】 == 报告错误时发生异常: ${error}`, "RecordSave");
}
}
// setInterval(interval: number, isForce = false) {
// // 保留接口,暂不实现动态调整
// }
/**
* 保存上传结果
*/
......@@ -686,8 +656,8 @@ class RecordSave {
this.endTask();
}
} catch (error) {
if (this._currentKey != null) {
this._addToBlackList(this._currentKey!.split("_")[0], `Save failed: ${error}`);
if (this._currentKey !== null) {
this._addToBlackList(this._currentKey.split("_")[0], `Save failed: ${error}`);
}
const recordId = data.recordId as string;
const filePath = data.filePath as string;
......@@ -713,8 +683,9 @@ class RecordSave {
this.canclePromises();
}
}
if (this._pumpTimer != null) {
clearTimeout(this._pumpTimer!);
const timer = this._pumpTimer;
if (timer !== null) {
clearTimeout(timer);
this._pumpTimer = null;
}
this._pumpTimer = setTimeout(() => {
......@@ -724,12 +695,13 @@ class RecordSave {
}
stopPolling() {
if (this.snapshot != null) {
this.snapshot!.clear();
this.snapshot = null;
if (this.snapshot !== null) {
this.snapshot.clear();
this.snapshot = null;
}
if (this._pumpTimer != null) {
clearTimeout(this._pumpTimer!);
const timer = this._pumpTimer;
if (timer !== null) {
clearTimeout(timer);
this._pumpTimer = null;
}
this.canclePromises();
......
......@@ -230,15 +230,15 @@ export class RecordService {
// --- 外部调用接口 ---
async saveAndClearRecord(isNotSave: boolean = false) {
if (this.record == null) return;
if (this.record === null) return;
if (isNotSave) {
logger.info("【录音服务RecordService】 == 不保存记录! ", "RecordService");
await this.record!.clearSavedFiles();
await this.record!.clearLocalRecord();
await this.record.clearSavedFiles();
await this.record.clearLocalRecord();
return;
}
await this.record!.setReceptionEndTime(); // 设置接待结束时间
await this.record!.save();
await this.record.setReceptionEndTime(); // 设置接待结束时间
await this.record.save();
}
/**
......@@ -319,7 +319,7 @@ export class RecordService {
async triggleTempNumber() {
if (this.record === null) return;
const _records = await this.record!.getRecords();
const _records = await this.record.getRecords();
// store.commit('audio/setPerRecordNumber', _records.length)
}
......@@ -338,7 +338,7 @@ export class RecordService {
if (result._isCache === true) {
const list = result.value as UTSJSONObject[];
if (this.record !== null) {
this.record!.cacheMaterialPoints(list); // 这里其实也可以泛化,比如 cache(key, val)
this.record.cacheMaterialPoints(list); // 这里其实也可以泛化,比如 cache(key, val)
}
} else {
this.record?.updatePreRecords(result);
......
......@@ -27,10 +27,10 @@ class TempRecord {
}
get db(): DBRecord {
if (this.dbRecord == null) {
if (this.dbRecord === null) {
this.dbRecord = DBRecord.getInstance();
}
return this.dbRecord!;
return this.dbRecord;
}
constructor(record: null | RecordData, onTempRecordNumberChanged: (() => void) | null, attributesProvider: (() => UTSJSONObject) | null) {
......@@ -46,10 +46,8 @@ class TempRecord {
* @returns {object} 新记录对象
*/
__createNewRecord(initialUrlList: RecordFile[]): RecordData {
console.log("🚀 ~ TempRecord ~ __createNewRecord ~ initialUrlList:", initialUrlList);
const dynamicAttributes = this.attributesProvider != null ? this.attributesProvider!() : {};
console.log("🚀 ~ TempRecord ~ __createNewRecord ~ dynamicAttributes:", dynamicAttributes);
const dynamicAttributes = this.attributesProvider?.() ?? {};
const newRec = {
id: getUUID(),
receptionStartTime: this.getTimeNow(),
......@@ -57,28 +55,13 @@ class TempRecord {
recordUrlList: initialUrlList,
recordStatus: 0
} as RecordData;
// merge this.newRecord and dynamicAttributes
// Use UTSJSONObject for merging to support dynamic keys
const resultJson = JSON.parse(JSON.stringify(newRec)) as UTSJSONObject;
console.log("🚀 ~ TempRecord ~ __createNewRecord ~ resultJson:", resultJson);
if (this.newRecord != null) {
const recordObj = JSON.parse(JSON.stringify(this.newRecord)) as UTSJSONObject;
const map = recordObj.toMap();
map.forEach((v, k) => {
resultJson[k] = v;
});
}
const dynMap = dynamicAttributes.toMap();
dynMap.forEach((v, k) => {
resultJson[k] = v;
});
// Convert back to RecordData
const res = JSON.parse<RecordData>(JSON.stringify(resultJson));
if (res == null) {
// 合并逻辑:新记录默认值 <- 现有记录(如有) <- 动态属性
// 使用 Object.assign 简化合并,最后统一深拷贝
const merged = Object.assign({}, newRec, this.newRecord ?? {}, dynamicAttributes);
const res = JSON.parse<RecordData>(JSON.stringify(merged));
if (res === null) {
throw new Error("Failed to parse RecordData");
}
return res;
......@@ -141,8 +124,7 @@ class TempRecord {
* @returns {Promise<void>|undefined} 值未变化时返回 undefined
*/
async __update(items: null | UTSJSONObject): Promise<void> {
if (this.record == null || items == null) return;
if (this.record === null || items === null) return;
// Convert to UTSJSONObject for dynamic property access
const currentRecordJson = JSON.parse(JSON.stringify(this.record)) as UTSJSONObject;
const updates = {} as UTSJSONObject;
......@@ -160,12 +142,12 @@ class TempRecord {
// nullValues is string?[] or (string|null)[]
// v is Any?
let isNotNullValue = true;
if (v == null) {
if (v === null) {
isNotNullValue = false;
} else {
// nullValues check manually
for (const nv of nullValues) {
if (nv == v) {
if (nv === v) {
isNotNullValue = false;
break;
}
......@@ -190,7 +172,7 @@ class TempRecord {
this.record = updatedRecord;
}
const id = this.record!.id;
const id = this.record.id;
await this.updateRecord(updates, { id });
}
}
......@@ -208,32 +190,31 @@ class TempRecord {
}
async addAudio(item: RecordFile) {
console.log("🚀 ~ TempRecord ~ addAudio ~ item:", item);
if (this.record == null) {
if (this.record === null) {
logger.warn("〖接待记录Record〗 == 尝试添加录音片段但 record 为空", "TempRecord");
return;
}
// const recordUrlList = (this.record!['recordUrlList'] as RecordFile[]) ?? []
const recordUrlList = (this.record!.recordUrlList as RecordFile[]) ?? [];
const recordUrlList = (this.record.recordUrlList as RecordFile[]) ?? [];
recordUrlList.push(item);
// 更新 record 对象中的列表,防止不同步
// this.record!['recordUrlList'] = recordUrlList
this.record!.recordUrlList = recordUrlList;
// 更新 record 对象中的列表,防止不同步
// this.record!['recordUrlList'] = recordUrlList
this.record.recordUrlList = recordUrlList;
// 更新数据库中的 recordUrlList
// const id = this.record!['id'] as string
const id = this.record!.id;
try {
// 更新数据库中的 recordUrlList
// const id = this.record!['id'] as string
const id = this.record.id;
try {
// Cast RecordFile[] to UTSJSONObject[] or any for updateRecord
// updateRecord takes UTSJSONObject for items
const updateData: UTSJSONObject = { recordUrlList };
await this.updateRecord(updateData, { id });
logger.info(`〖接待记录Record〗 == 新增录音片段: ${JSON.stringify(item)}`, "TempRecord");
} catch (error) {
} catch (error) {
logger.error(`〖接待记录Record〗 == 新增录音片段失败: ${error}`, "TempRecord");
throw error; // 抛出异常以便上层捕获
}
}
}
/**
......@@ -243,7 +224,7 @@ class TempRecord {
*/
async addRecord(record: null | RecordData = null) {
const rec = record ?? this.record;
if (rec == null) return;
if (rec === null) return;
try {
// Cast RecordData to UTSJSONObject for DB operation if necessary,
......@@ -303,18 +284,18 @@ class TempRecord {
* @param {Array} list
*/
cacheMaterialPoints(list: UTSJSONObject[]) {
if (this.record != null && this.record!.id != "") {
RecordCache.set(this.record!.id, "MATERIAL_POINTS", list);
if (this.record !== null && this.record.id !== "") {
RecordCache.set(this.record.id, "MATERIAL_POINTS", list);
}
}
async clearLocalRecord(record: null | RecordData = null, removeDbRecord = true) {
const rec = record ?? this.record;
if (rec == null) return;
if (rec === null) return;
const id = rec.id;
if (id != "" && removeDbRecord) {
if (id !== "" && removeDbRecord) {
await this.removeRecord(id);
}
RecordCache.clearAll(id);
......@@ -328,10 +309,10 @@ class TempRecord {
* @returns {void}
*/
clearLoopTimer() {
if (this.timer != null) {
clearInterval(this.timer!);
this.timer = null;
}
// if (this.timer !== null) {
// clearInterval(this.timer);
// this.timer = null;
// }
}
/**
* 清除已保存的录音文件
......@@ -372,7 +353,7 @@ class TempRecord {
}
async destroy() {
this._isDestroyed = true;
this.clearLoopTimer();
// this.clearLoopTimer();
logger.info("〖接待记录Record〗 == TempRecord 实例已销毁", "TempRecord");
}
......@@ -476,8 +457,8 @@ class TempRecord {
* @returns {Promise<void>|void}
*/
async triggleRecordNumChanged() {
if (this.onTempRecordNumberChanged != null) {
this.onTempRecordNumberChanged!();
if (this.onTempRecordNumberChanged !== null) {
this.onTempRecordNumberChanged();
}
}
......
const WsTyps = {
MessageTypes: {
Private: 'private',
System: 'system'
},
Connected:'connect',
Eroor:'error',
Disconnected:'disconnect'
}
MessageTypes: {
Private: "private",
System: "system"
},
Connected:"connect",
Eroor:"error",
Disconnected:"disconnect"
};
const FileStatus = {
Error:0,
NoFile:1,
Waiting:2,
Uploading:3,
NotExist:4,
Uploaded:5,
Completed:6, //状态4 的 完成状态
HasFile:999 // 有文件的记录
}
Error:0,
NoFile:1,
Waiting:2,
Uploading:3,
NotExist:4,
Uploaded:5,
Completed:6, // 状态4 的 完成状态
HasFile:999 // 有文件的记录
};
export {
WsTyps,
FileStatus
}
FileStatus,
WsTyps
};
......@@ -9,7 +9,7 @@ import { IRecorderStrategy } from "../types/strategy.uts";
export class DefaultRecorderStrategy implements IRecorderStrategy {
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.轻改
}
/**
......@@ -41,10 +41,6 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
}
}
getName(): string {
return "DefaultCarSalesStrategy";
}
/**
* 获取需要解析为 JSON 的字段
*/
......@@ -55,6 +51,10 @@ export class DefaultRecorderStrategy implements IRecorderStrategy {
];
}
getName(): string {
return "DefaultCarSalesStrategy";
}
/**
* 获取业务字段定义
*/
......
import type { OssTokenData } from "./types/oss.uts";
import { getToken } from "@/api/receiption.uts";
import { OSS_CONFIG } from "@/config/oss.config.uts";
import { logger } from "../logger/index.uts";
import { IUploadStrategy } from "./IUploadStrategy.uts";
......@@ -27,7 +28,7 @@ export abstract class AliOSSBaseStrategy implements IUploadStrategy {
async upload(options: UTSJSONObject): Promise<UTSJSONObject> {
const filePath = options.getString("filePath");
if (filePath == null || filePath == "") {
if (filePath === null || filePath === "") {
throw new Error("filePath is required");
}
......@@ -37,13 +38,12 @@ export abstract class AliOSSBaseStrategy implements IUploadStrategy {
try {
// 1. 获取 OSS Token
const responseJson = await getToken({});
console.log("🚀 ~ AliOSSBaseStrategy ~ upload ~ responseJson:", responseJson);
let token: null | OssTokenData = null;
// 手动解析 JSON,避免 Gson 强类型检查导致的 "non-nullable member" 错误
const dataObj = responseJson.data;
if (dataObj != null && typeof dataObj === "object") {
if (dataObj !== null && typeof dataObj === "object") {
// 标准结构: { code, msg, data: {...} }
const data = dataObj as UTSJSONObject;
token = {
......@@ -56,7 +56,7 @@ export abstract class AliOSSBaseStrategy implements IUploadStrategy {
} else {
// 尝试直接映射: { lsaccessKeyId, ... }
const lsaccessKeyId = responseJson.getString("lsaccessKeyId");
if (lsaccessKeyId != null) {
if (lsaccessKeyId !== null) {
token = {
lsaccessKeyId,
lsaccessKeySecret: responseJson.getString("lsaccessKeySecret"),
......@@ -67,15 +67,23 @@ export abstract class AliOSSBaseStrategy implements IUploadStrategy {
}
}
if (token == null || token.lsaccessKeyId == null || token.lsaccessKeyId == "") {
if (token === null || token.lsaccessKeyId === null || token.lsaccessKeyId === "") {
// 记录原始响应以便调试 (使用 console.error 避免 logger 可能的异常)
console.error(`[${strategyName}] Token响应无效:`, JSON.stringify(responseJson));
throw new Error("Token response is invalid or null");
}
// 设置默认值
if (token.bucketName === null || token.bucketName === "") {
token.bucketName = OSS_CONFIG.getString("defaultBucket");
}
if (token.region === null || token.region === "") {
token.region = OSS_CONFIG.getString("defaultRegion");
}
// 2. 确定 objectKey
let objectKey = options.getString("objectKey");
if (objectKey == null || objectKey == "") {
if (objectKey === null || objectKey === "") {
const fileName = filePath.slice(Math.max(0, filePath.lastIndexOf("/") + 1));
objectKey = `uploads/${Date.now()}/${fileName}`;
}
......
import { UploadOptions, upload, initConfig, OSSConfig, UploadSuccessResult, UploadFailResult } from "@/uni_modules/uts-alioss";
import { logger } from '../logger/index.uts'
import { AliOSSBaseStrategy } from './AliOSSBaseStrategy.uts'
import type { OssTokenData } from './types/oss.uts'
import type { OssTokenData } from "./types/oss.uts";
import { OSSConfig, upload, UploadFailResult, UploadOptions, UploadSuccessResult } from "@/uni_modules/uts-alioss";
import { logger } from "../logger/index.uts";
import { AliOSSBaseStrategy } from "./AliOSSBaseStrategy.uts";
/**
* 阿里云 OSS 上传策略 (原生 SDK)
*/
export class AliOSSUploadStrategy extends AliOSSBaseStrategy {
constructor() {
super()
}
override getStrategyName(): string {
return "AliOSSUploadStrategy"
}
constructor() {
super();
}
override async doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UTSJSONObject): Promise<UTSJSONObject> {
const lsaccessKeySecret:string = token.lsaccessKeySecret ?? ""
const securityToken:string = token.securityToken ?? ""
const lsaccessKeyId:string = token.lsaccessKeyId ?? ""
override async doUpload(filePath: string, objectKey: string, token: OssTokenData, options: UTSJSONObject): Promise<UTSJSONObject> {
const lsaccessKeySecret:string = token.lsaccessKeySecret ?? "";
const securityToken:string = token.securityToken ?? "";
const lsaccessKeyId:string = token.lsaccessKeyId ?? "";
// 使用默认值如果未定义
const defaultBucket:string = token.bucketName ?? 'glsk-oss'
const defaultRegion:string = token.region ?? 'oss-cn-shenzhen'
// 允许 options 覆盖默认配置
const bucketName:string = options.getString('bucketName') ?? defaultBucket
const region:string = options.getString('region') ?? defaultRegion
const bucketName = options.getString("bucketName") ?? token.bucketName??"";
const region = options.getString("region") ?? token.region??"";
// 配置 OSS
const ossConfig = {
endpoint: `https://${region}.aliyuncs.com`,
bucketName: bucketName,
accessKeyId: lsaccessKeyId , // 必填
accessKeySecret: lsaccessKeySecret , // 必填
securityToken: securityToken // 选填
} as OSSConfig
// 配置 OSS
const ossConfig = {
endpoint: `https://${region}.aliyuncs.com`,
bucketName,
accessKeyId: lsaccessKeyId, // 必填
accessKeySecret: lsaccessKeySecret, // 必填
securityToken // 选填
} as OSSConfig;
initConfig(ossConfig)
// initConfig(ossConfig);
// 使用 await 等待 Promise 结果
const result = await new Promise<UTSJSONObject>((resolve, reject) => {
const uploadOptions = {
filePath: filePath,
objectKey: objectKey,
success: (res: UploadSuccessResult) => {
logger.info(`[AliOSSUploadStrategy] 上传成功: ${res.url}`, "FileUploadService")
resolve({
url: res.url,
objectKey: res.objectKey,
strategy: 'alioss'
} as UTSJSONObject)
},
fail: (res: UploadFailResult) => {
logger.error(`[AliOSSUploadStrategy] 上传失败: code=${res.errCode}, msg=${res.errMsg}`, "FileUploadService")
reject(new Error(res.errMsg))
}
} as UploadOptions
// 使用 await 等待 Promise 结果
const result = await new Promise<UTSJSONObject>((resolve, reject) => {
const uploadOptions = {
filePath,
objectKey,
success: (res: UploadSuccessResult) => {
logger.info(`[AliOSSUploadStrategy] 上传成功: ${res.url}`, "FileUploadService");
resolve({
url: res.url,
objectKey: res.objectKey,
strategy: "alioss"
} as UTSJSONObject);
},
fail: (res: UploadFailResult) => {
logger.error(`[AliOSSUploadStrategy] 上传失败: code=${res.errCode}, msg=${res.errMsg}`, "FileUploadService");
reject(new Error(res.errMsg));
}
} as UploadOptions;
upload(uploadOptions)
})
upload(uploadOptions);
});
return result
}
return result;
}
override getStrategyName(): string {
return "AliOSSUploadStrategy";
}
}
......@@ -20,13 +20,9 @@ export class AliUniUploadStrategy extends AliOSSBaseStrategy {
const accessKeySecret = token.lsaccessKeySecret ?? "";
const securityToken = token.securityToken ?? "";
// 默认配置
const defaultBucket = token.bucketName ?? "glsk-oss";
const defaultRegion = token.region ?? "oss-cn-shenzhen";
// 允许 options 覆盖
const bucketName = options.getString("bucketName") ?? defaultBucket;
const region = options.getString("region") ?? defaultRegion;
// 允许 options 覆盖 (token.bucketName/region 已经在 BaseStrategy 中确保有值)
const bucketName = options.getString("bucketName") ?? token.bucketName;
const region = options.getString("region") ?? token.region;
// 3. 生成 Policy 和 Signature
const host = `https://${bucketName}.${region}.aliyuncs.com`;
......
import { logger } from '../logger/index.uts'
import { IUploadStrategy } from './IUploadStrategy.uts'
import { logger } from "../logger/index.uts";
import { IUploadStrategy } from "./IUploadStrategy.uts";
/**
* uni.uploadFile 上传策略
*/
export class UniUploadStrategy implements IUploadStrategy {
async upload(options: UTSJSONObject): Promise<UTSJSONObject> {
const filePath = options.getString('filePath')
if (filePath == null || filePath == "") {
throw new Error("filePath is required")
}
async upload(options: UTSJSONObject): Promise<UTSJSONObject> {
const filePath = options.getString("filePath");
if (filePath == null || filePath == "") {
throw new Error("filePath is required");
}
const uploadUrl = options.getString('uploadUrl')
if (uploadUrl == null || uploadUrl == "") {
throw new Error("uploadUrl is required for UniUploadStrategy")
}
const uploadUrl = options.getString("uploadUrl");
if (uploadUrl == null || uploadUrl == "") {
throw new Error("uploadUrl is required for UniUploadStrategy");
}
logger.info(`[UniUploadStrategy] 开始上传文件: ${filePath} to ${uploadUrl}`, "FileUploadService")
logger.info(`[UniUploadStrategy] 开始上传文件: ${filePath} to ${uploadUrl}`, "FileUploadService");
try {
const result = await new Promise<UTSJSONObject>((resolve, reject) => {
uni.uploadFile({
url: uploadUrl,
filePath: filePath,
name: options.getString('name') ?? 'file',
formData: options['formData'] as UTSJSONObject,
header: options['header'] as UTSJSONObject,
success: (res) => {
logger.info(`[UniUploadStrategy] 上传成功: ${res.statusCode}`, "FileUploadService")
try {
const result = await new Promise<UTSJSONObject>((resolve, reject) => {
uni.uploadFile({
url: uploadUrl,
filePath,
name: options.getString("name") ?? "file",
formData: options.formData as UTSJSONObject,
header: options.header as UTSJSONObject,
success: (res) => {
logger.info(`[UniUploadStrategy] 上传成功: ${res.statusCode}`, "FileUploadService");
let data: UTSJSONObject
try {
if (typeof res.data === 'string') {
data = JSON.parse(res.data as string) as UTSJSONObject
} else {
data = res.data as UTSJSONObject
}
} catch (e) {
data = { rawData: res.data }
}
let data: UTSJSONObject;
try {
if (typeof res.data === "string") {
data = JSON.parse(res.data as string) as UTSJSONObject;
} else {
data = res.data as UTSJSONObject;
}
} catch {
data = { rawData: res.data };
}
// 统一返回结构,尽量包含 url 字段如果服务端返回了
// 这里假设服务端返回的数据中可能包含 url,或者直接返回整个 data
data['strategy'] = 'uni'
data['statusCode'] = res.statusCode
// 统一返回结构,尽量包含 url 字段如果服务端返回了
// 这里假设服务端返回的数据中可能包含 url,或者直接返回整个 data
data.strategy = "uni";
data.statusCode = res.statusCode;
resolve(data)
},
fail: (err) => {
logger.error(`[UniUploadStrategy] 上传失败: ${err.errMsg}`, "FileUploadService")
reject(new Error(err.errMsg))
}
})
})
return result
} catch (error) {
const errorMsg = typeof error === 'string' ? error : `${error}`
logger.error(`[UniUploadStrategy] 上传异常: ${errorMsg}`, "FileUploadService")
throw error
}
}
resolve(data);
},
fail: (err) => {
logger.error(`[UniUploadStrategy] 上传失败: ${err.errMsg}`, "FileUploadService");
reject(new Error(err.errMsg));
}
});
});
return result;
} catch (error) {
const errorMsg = typeof error === "string" ? error : `${error}`;
logger.error(`[UniUploadStrategy] 上传异常: ${errorMsg}`, "FileUploadService");
throw error;
}
}
}
export type OssTokenData = {
bucketName?: string
lsaccessKeyId?: string
lsaccessKeySecret?: string
securityToken?: string
bucketName?: string
region?: string
securityToken?: string
}
export type OssTokenResponse = {
code: string
msg: string
data: OssTokenData
msg: string
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!