Commit d053d859 by liimin

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

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