Commit c8ac617f by liimin

refactor(logger): 重构日志模块以提升可维护性和性能

- 引入 LoggerCore 作为核心日志类,统一管理日志输出策略
- 新增 LocalFileLogStore 处理本地文件存储,优化日志写入性能
- 新增 LogUploadService 提供独立的日志上传服务
- 重构文件上传服务,支持动态策略切换和错误处理
- 移除对外部日志插件的依赖,实现自主可控的日志体系
- 优化工具函数,移除不必要的类型忽略注释
1 parent 991d9ad6
import { UploadConfig } from "@/services/logger/index"; import { UploadConfig } from "@/services/logger/index";
export const LoggerUploadServerUrl: string = "http://192.168.1.237:3000/file/upload";
export const LoggerUploadHeaders: null | UTSJSONObject = null;
export const LoggerUploadDays: number = 7;
/** /**
* 日志服务默认配置 * 日志服务默认配置
*/ */
...@@ -12,16 +16,16 @@ export const LoggerConfig = { ...@@ -12,16 +16,16 @@ export const LoggerConfig = {
/** /**
* 上传服务器地址 * 上传服务器地址
*/ */
serverUrl: "http://192.168.1.237:3000/file/upload", serverUrl: LoggerUploadServerUrl,
/** /**
* 默认请求头 * 默认请求头
*/ */
headers: null, headers: LoggerUploadHeaders,
/** /**
* 默认上传最近几天的日志 * 默认上传最近几天的日志
*/ */
days: 7 days: LoggerUploadDays
} as UploadConfig } as UploadConfig
}; };
/* eslint-disable unicorn/text-encoding-identifier-case */
import { checkFileExists, createDirectory, readDirectory, readFile, writeFile } from "@/utils/plus-io.uts";
export class LocalFileLogStore {
private static instance: LocalFileLogStore | null = null;
private readonly dirPath: string;
private flushing: boolean = false;
private initialized: boolean = false;
private pending: string[] = [];
private constructor() {
const userDataPath = uni.env.USER_DATA_PATH;
this.dirPath = this.resolveLogDirPath(userDataPath);
}
static getInstance(): LocalFileLogStore {
if (LocalFileLogStore.instance == null) {
LocalFileLogStore.instance = new LocalFileLogStore();
}
return LocalFileLogStore.instance;
}
getLogDirPath(): string {
return this.dirPath;
}
async getLogFiles(days: number = 7): Promise<string[]> {
await this.flush();
await this.init();
return this.filterLogFiles(days);
}
async getLogFilesByDate(date: string): Promise<string[]> {
await this.flush();
await this.init();
const names = await readDirectory(this.dirPath).catch((): string[] => []);
const result: string[] = [];
for (const name of names) {
if (!name.startsWith("log_") || !name.endsWith(".txt")) continue;
const datePart = name.slice(4, 14);
if (datePart == date) {
result.push(`${this.dirPath}/${name}`);
}
}
return result;
}
async init(): Promise<void> {
if (this.initialized) return;
try {
const exists = await checkFileExists(this.dirPath);
if (!exists) {
await createDirectory(this.dirPath, true);
}
this.initialized = true;
} catch {
this.initialized = true;
}
}
writeLine(level: string, tag: string, msg: string) {
const now = new Date();
const timestamp = this.formatDateTime(now);
this.pending.push(`${timestamp} [${level}] [${tag}] ${msg}`);
this.scheduleFlush();
}
private async appendText(path: string, text: string): Promise<void> {
const fs = uni.getFileSystemManager();
try {
await new Promise<void>((resolve, reject) => {
fs.appendFile({
filePath: path,
data: text,
encoding: "utf-8",
success: () => resolve(),
fail: (err: any) => reject(err)
});
});
} catch {
const exists = await checkFileExists(path);
const original = exists ? await readFile(path, "utf-8").catch((): string => "") : "";
await writeFile(path, `${original}${text}`);
}
}
private async filterLogFiles(days: number): Promise<string[]> {
await this.init();
const names = await readDirectory(this.dirPath).catch((): string[] => []);
const result: string[] = [];
const cutoff = new Date();
cutoff.setHours(0, 0, 0, 0);
if (days > 0) {
cutoff.setDate(cutoff.getDate() - (days - 1));
}
for (const name of names) {
if (!name.startsWith("log_") || !name.endsWith(".txt")) continue;
const datePart = name.slice(4, 14);
const fileDate = new Date(`${datePart}T00:00:00`);
if (days <= 0 || fileDate.getTime() >= cutoff.getTime()) {
result.push(`${this.dirPath}/${name}`);
}
}
return result;
}
private async flush(): Promise<void> {
await this.init();
try {
while (this.pending.length > 0) {
const chunk = this.pending.splice(0, 50);
const text = `${chunk.join("\n")}\n`;
await this.appendText(this.getCurrentFilePath(), text);
}
} catch {} finally {
this.flushing = false;
if (this.pending.length > 0) {
this.scheduleFlush();
}
}
}
private formatDate(date: Date): string {
const yyyy = date.getFullYear();
const MM = `${date.getMonth() + 1}`.padStart(2, "0");
const dd = `${date.getDate()}`.padStart(2, "0");
return `${yyyy}-${MM}-${dd}`;
}
private formatDateTime(date: Date): string {
const yyyy = date.getFullYear();
const MM = `${date.getMonth() + 1}`.padStart(2, "0");
const dd = `${date.getDate()}`.padStart(2, "0");
const HH = `${date.getHours()}`.padStart(2, "0");
const mm = `${date.getMinutes()}`.padStart(2, "0");
const ss = `${date.getSeconds()}`.padStart(2, "0");
const SSS = `${date.getMilliseconds()}`.padStart(3, "0");
return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}.${SSS}`;
}
private getCurrentFilePath(): string {
const day = this.formatDate(new Date());
return `${this.dirPath}/log_${day}.txt`;
}
private resolveLogDirPath(userDataPath: null | string): string {
if (userDataPath === null || userDataPath === "") {
return "files/logs";
}
let basePath = userDataPath.replaceAll("\\", "/");
while (basePath.endsWith("/")) {
basePath = basePath.slice(0, Math.max(0, basePath.length - 1));
}
if (basePath === "unifile://usr" || basePath.endsWith("/usr")) {
return `${basePath}/files/logs`;
}
if (basePath.endsWith("/files")) {
return `${basePath}/logs`;
}
return `${basePath}/logs`;
}
private scheduleFlush() {
if (this.flushing) return;
this.flushing = true;
Promise.resolve().then(async (): Promise<void> => {
await this.flush();
});
}
}
import { LoggerUploadDays, LoggerUploadHeaders, LoggerUploadServerUrl } from "@/config/logger.config.uts";
import { handleError } from "@/utils/error.uts";
import { createDirectory, deleteFile, readFile, writeFile } from "@/utils/plus-io.uts";
import FileUploadService from "../uploader/FileUploadService.uts";
import { UploadStrategyType } from "../uploader/types/upload.uts";
import { Logger } from "./LoggerCore";
export type LogUploadOptions = {
date?: string
days?: number
deviceId?: number
headers?: null | UTSJSONObject
name?: string
serverUrl?: string
}
export type LogUploadItemResult = {
error?: null | string
filePath: string
result?: null | UTSJSONObject
success: boolean
}
export type LogUploadResult = {
failCount: number
items: LogUploadItemResult[]
successCount: number
total: number
uploadedUrls: string[]
}
const logger = Logger.getInstance();
function getFileName(filePath: string): string {
const index = filePath.lastIndexOf("/");
if (index === -1) {
return filePath;
}
return filePath.slice(index + 1);
}
function getDirPath(filePath: string): string {
const index = filePath.lastIndexOf("/");
if (index === -1) {
return filePath;
}
return filePath.slice(0, index);
}
async function createUploadSnapshot(filePath: string): Promise<string> {
try {
// eslint-disable-next-line unicorn/text-encoding-identifier-case
const content = await readFile(filePath, "utf-8");
const dirPath = getDirPath(filePath);
const tempDir = `${dirPath}/upload_tmp`;
await createDirectory(tempDir, true).catch((): void => {});
const fileName = getFileName(filePath).replace(".txt", "");
const snapshotPath = `${tempDir}/${fileName}.txt`;
await writeFile(snapshotPath, content);
return snapshotPath;
} catch {
return filePath;
}
}
async function uploadFileByUniFallback(
filePath: string,
serverUrl: string,
headers: null | UTSJSONObject,
parameters: UTSJSONObject
): Promise<UTSJSONObject> {
try {
const uploadOptions = {
filePath,
uploadUrl: serverUrl,
formData: parameters,
header: headers != null ? headers : {} as UTSJSONObject
} as UTSJSONObject;
const rawResult = await FileUploadService.upload(uploadOptions, UploadStrategyType.UNI_UPLOAD);
let data = {} as UTSJSONObject;
try {
data = JSON.parse(JSON.stringify(rawResult)) as UTSJSONObject;
} catch {
try {
data = new UTSJSONObject(rawResult);
} catch {}
}
const statusCode = data.statusCode;
return {
success: true,
message: "上传成功",
data,
statusCode: statusCode != null ? statusCode : 200,
strategy: "uni"
} as UTSJSONObject;
} catch (error: any) {
let errorMsg = "上传失败";
try {
const text = JSON.stringify(error);
if (text != null && text != "") {
errorMsg = text;
}
} catch {
errorMsg = `${error}`;
}
return {
success: false,
message: errorMsg,
data: {} as UTSJSONObject,
strategy: "uni"
} as UTSJSONObject;
}
}
export async function uploadLogs(options: LogUploadOptions | null = null): Promise<LogUploadResult> {
let serverUrl = LoggerUploadServerUrl;
let days = LoggerUploadDays;
let deviceId: null | number = null;
let headers = LoggerUploadHeaders;
let date: null | string = null;
if (options != null) {
if (options.serverUrl != null && options.serverUrl != "") {
serverUrl = options.serverUrl;
}
if (typeof options.days === "number") {
days = options.days as number;
}
if (options.headers != null) {
headers = options.headers;
}
if (typeof options.deviceId === "number") {
deviceId = options.deviceId as number;
}
if (options.date != null && options.date != "") {
date = options.date;
}
}
if (serverUrl == null || serverUrl == "") {
logger.warn("〖日志上传跳过〗未配置 serverUrl", "LoggerUpload");
return {
failCount: 0,
items: [],
successCount: 0,
total: 0,
uploadedUrls: []
};
}
if (deviceId == null) {
logger.warn("〖日志上传跳过〗未传入 deviceId", "LoggerUpload");
return {
failCount: 0,
items: [],
successCount: 0,
total: 0,
uploadedUrls: []
};
}
let files: string[] = [];
if (date != null) {
files = await logger.getLogFilesByDate(date);
} else {
files = await logger.getLogFiles(days);
}
if (files.length === 0) {
logger.info("〖日志上传跳过〗未找到可上传日志文件", "LoggerUpload");
return {
failCount: 0,
items: [],
successCount: 0,
total: 0,
uploadedUrls: []
};
}
logger.info(`〖日志上传开始〗数量: ${files.length}`, "LoggerUpload");
const items: LogUploadItemResult[] = [];
const uploadedUrls: string[] = [];
let successCount = 0;
let failCount = 0;
for (const filePath of files) {
let uploadPath = filePath;
let snapshotPath: null | string = null;
try {
const createdSnapshotPath = await createUploadSnapshot(filePath);
if (createdSnapshotPath != filePath) {
uploadPath = createdSnapshotPath;
snapshotPath = createdSnapshotPath;
}
const parameters = {
deviceId,
type: "log"
} as UTSJSONObject;
const result = await uploadFileByUniFallback(uploadPath, serverUrl, headers, parameters);
const message = result.message;
const isSuccess = result.success === true;
if (isSuccess !== true) {
failCount += 1;
const errorMsg = message != null ? `${message}` : "上传失败";
items.push({
error: errorMsg,
filePath,
result,
success: false
});
logger.error(`〖日志上传失败〗${filePath}, error: ${errorMsg}`, "LoggerUpload");
continue;
}
successCount += 1;
try {
const payload = result.data;
const payloadObj = payload != null && typeof payload === "object" ? payload as UTSJSONObject : null;
const dataNode = payloadObj != null ? payloadObj.data : null;
const dataObj = dataNode != null && typeof dataNode === "object" ? dataNode as UTSJSONObject : null;
const path = dataObj != null ? dataObj.path : null;
const url = dataObj != null ? dataObj.url : null;
const resolvedUrl = path != null && `${path}` != "" ? `${path}` : (url != null ? `${url}` : "");
if (resolvedUrl != "") {
uploadedUrls.push(resolvedUrl);
}
} catch {}
items.push({
filePath,
result,
success: true
});
logger.info(`〖日志上传成功〗${filePath} => ${JSON.stringify(result)}`, "LoggerUpload");
} catch (error: any) {
failCount += 1;
const errorMsg = handleError(error, "LoggerUpload", `〖日志上传失败〗${filePath}, error:`);
items.push({
error: errorMsg,
filePath,
success: false
});
} finally {
if (snapshotPath != null) {
await deleteFile(snapshotPath).catch((): void => {});
}
}
}
return {
failCount,
items,
successCount,
total: files.length,
uploadedUrls
};
}
import { LocalFileLogStore } from "./LocalFileLogStore";
import { RemoteLog, RemoteLogOptions, Tag, UserInfo } from "./RemoteLog";
type LogAction = (msg: string) => void
type RemoteAction = (opts: RemoteLogOptions) => void
type LogStrategyAction = {
console: LogAction
remote: (r: RemoteLog) => RemoteAction
}
export class Logger {
private static instance: Logger | null = null;
private actions: Map<string, LogStrategyAction> = new Map();
private fileStore: LocalFileLogStore = LocalFileLogStore.getInstance();
private remote: null | RemoteLog = null;
private constructor() {
this.actions = new Map([
["DEBUG", { console: (msg: string) => { console.log(msg); }, remote: (r: RemoteLog) => (opts: RemoteLogOptions) => { r.debug(opts); } } as LogStrategyAction],
["ERROR", { console: (msg: string) => { console.error(msg); }, remote: (r: RemoteLog) => (opts: RemoteLogOptions) => { r.error(opts); } } as LogStrategyAction],
["INFO", { console: (msg: string) => { console.log(msg); }, remote: (r: RemoteLog) => (opts: RemoteLogOptions) => { r.info(opts); } } as LogStrategyAction],
["WARN", { console: (msg: string) => { console.warn(msg); }, remote: (r: RemoteLog) => (opts: RemoteLogOptions) => { r.warn(opts); } } as LogStrategyAction]
]);
this.fileStore.init();
}
static getInstance(): Logger {
if (Logger.instance == null) {
Logger.instance = new Logger();
}
return Logger.instance;
}
debug(msg: any, tag: string = "App") { this.log("DEBUG", msg, tag); }
error(msg: any, tag: string = "App") { this.log("ERROR", msg, tag); }
getLogDirPath(): string {
return this.fileStore.getLogDirPath();
}
getLogFiles(days: number = 7): Promise<string[]> {
return this.fileStore.getLogFiles(days);
}
getLogFilesByDate(date: string): Promise<string[]> {
return this.fileStore.getLogFilesByDate(date);
}
info(msg: any, tag: string = "App") { this.log("INFO", msg, tag); }
init(user: UserInfo) {
this.remote = new RemoteLog(user);
this.info(`Logger initialized for user: ${user.name} (${user.id})`, "Logger");
}
warn(msg: any, tag: string = "App") { this.log("WARN", msg, tag); }
private formatMsg(msg: any): string {
if (typeof msg === "string") return msg;
try { return JSON.stringify(msg); } catch { return `${msg}`; }
}
private log(level: string, msg: any, tag: string) {
const action = this.actions.get(level);
if (action == null) return;
const message = this.formatMsg(msg);
const fullMessage = `[${level}][${tag}] ${message}`;
let consoleMessage = fullMessage;
const ESC = "\u001B";
const RESET = `${ESC}[0m`;
if (level == "DEBUG") {
consoleMessage = `${ESC}[34m${fullMessage}${RESET}`;
} else if (level == "INFO") {
consoleMessage = `${ESC}[32m${fullMessage}${RESET}`;
} else if (level == "WARN") {
consoleMessage = `${ESC}[93m${fullMessage}${RESET}`;
} else if (level == "ERROR") {
consoleMessage = `${ESC}[31m${fullMessage}${RESET}`;
}
action.console(consoleMessage);
this.fileStore.writeLine(level, tag, message);
this.remote?.let((r) => {
action.remote(r)({ msg: message, tag: { key: "module", value: tag } as Tag } as RemoteLogOptions);
});
}
}
import { LoggerConfig } from "@/config/logger.config"; import { Logger } from "./LoggerCore";
import { initLog, IReturn, IUpload, logError, logInfo, logWarn, setUser, uploadLog, uploadZip } from "@/uni_modules/ima-log";
export { Logger } from "./LoggerCore";
import { RemoteLog, RemoteLogOptions, Tag, UserInfo } from "./RemoteLog"; export type UploadConfig = {
days?: number
export type UploadConfig = { days?: number, headers?: null | UTSJSONObject, serverUrl: string } deviceId?: number
headers?: null | UTSJSONObject
type LogAction = (msg: string) => void serverUrl: string
type RemoteAction = (opts: RemoteLogOptions) => void
type LogStrategyAction = {
console: LogAction
file: LogAction
remote: (r: RemoteLog) => RemoteAction
} }
export * from "./LogUploadService";
export class Logger {
private static instance: Logger | null = null;
// 定义操作映射表,消除 switch/if
private actions: Map<string, LogStrategyAction> = new Map([
["DEBUG", { console: (msg: string) => { console.log(msg); }, file: (msg: string) => { logInfo(msg); }, remote: (r: RemoteLog) => (opts: RemoteLogOptions) => { r.debug(opts); } } as LogStrategyAction],
["ERROR", { console: (msg: string) => { console.error(msg); }, file: (msg: string) => { logError(msg); }, remote: (r: RemoteLog) => (opts: RemoteLogOptions) => { r.error(opts); } } as LogStrategyAction],
["INFO", { console: (msg: string) => { console.log(msg); }, file: (msg: string) => { logInfo(msg); }, remote: (r: RemoteLog) => (opts: RemoteLogOptions) => { r.info(opts); } } as LogStrategyAction],
["WARN", { console: (msg: string) => { console.warn(msg); }, file: (msg: string) => { logWarn(msg); }, remote: (r: RemoteLog) => (opts: RemoteLogOptions) => { r.warn(opts); } } as LogStrategyAction]
]);
private remote: null | RemoteLog = null;
private uploadConfig: UploadConfig = LoggerConfig.upload as UploadConfig;
private constructor() {
initLog(0).then((res: IReturn) => console.log("[Logger] initLog result:", res));
}
static getInstance(): Logger {
if (Logger.instance == null) {
Logger.instance = new Logger();
}
return Logger.instance;
}
debug(msg: any, tag: string = "App") { this.log("DEBUG", msg, tag); }
error(msg: any, tag: string = "App") { this.log("ERROR", msg, tag); }
info(msg: any, tag: string = "App") { this.log("INFO", msg, tag); }
init(user: UserInfo) {
this.remote = new RemoteLog(user);
setUser(user.id).then((res: IReturn) => console.log("[Logger] setUser result:", res));
this.info(`Logger initialized for user: ${user.name} (${user.id})`, "Logger");
}
setUploadConfig(config: UploadConfig) { this.uploadConfig = config; }
upload(serverUrl: string = "", headers: null | UTSJSONObject = null, days: number = 0): Promise<IReturn> {
return this.doUpload(serverUrl, headers, days, "zip", (opts: IUpload, cb: ((res: IReturn) => void) | null): Promise<IReturn> => uploadZip(opts, cb));
}
uploadRaw(serverUrl: string = "", headers: null | UTSJSONObject = null, days: number = 0): Promise<IReturn> {
return this.doUpload(serverUrl, headers, days, "log", (opts: IUpload, cb: ((res: IReturn) => void) | null): Promise<IReturn> => uploadLog(opts, cb));
}
warn(msg: any, tag: string = "App") { this.log("WARN", msg, tag); }
private doUpload(url: string, headers: null | UTSJSONObject, days: number, suffix: string, uploadFn: (opts: IUpload, cb: ((res: IReturn) => void) | null) => Promise<IReturn>): Promise<IReturn> {
const targetUrl = url === "" ? this.uploadConfig.serverUrl : url;
if (targetUrl === "") return Promise.resolve({ success: false, message: "Server URL not configured" } as IReturn);
const options = {
serverUrl: targetUrl,
headers: headers ?? this.uploadConfig.headers,
include: true,
days: (days == 0 ? this.uploadConfig.days : days) ?? 7,
suffix
} as IUpload;
return uploadFn(options, null);
}
private formatMsg(msg: any): string {
if (typeof msg === "string") return msg;
try { return JSON.stringify(msg); } catch { return `${msg}`; }
}
private log(level: string, msg: any, tag: string) {
const action = this.actions.get(level);
if (action == null) return;
const message = this.formatMsg(msg);
const fullMessage = `[${level}][${tag}] ${message}`;
// Add ANSI color codes for console output
let consoleMessage = fullMessage;
const ESC = "\u001B";
const RESET = `${ESC}[0m`;
if (level == "DEBUG") {
consoleMessage = `${ESC}[34m${fullMessage}${RESET}`; // Blue
} else if (level == "INFO") {
consoleMessage = `${ESC}[32m${fullMessage}${RESET}`; // Green
} else if (level == "WARN") {
consoleMessage = `${ESC}[93m${fullMessage}${RESET}`; // Bright Yellow
} else if (level == "ERROR") {
consoleMessage = `${ESC}[31m${fullMessage}${RESET}`; // Red
}
action.console(consoleMessage);
action.file(fullMessage);
this.remote?.let((r) => {
action.remote(r)({ msg: message, tag: { key: "module", value: tag } as Tag } as RemoteLogOptions);
});
}
}
export const logger = Logger.getInstance(); export const logger = Logger.getInstance();
...@@ -6,13 +6,15 @@ ...@@ -6,13 +6,15 @@
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\uploader\FileUploadService.uts * @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\uploader\FileUploadService.uts
*/ */
import { logger } from "../logger/index.uts"; import { Logger } from "../logger/LoggerCore.uts";
import { AliOSSUploadStrategy } from "./strategies/AliOSSUploadStrategy.uts"; import { AliOSSUploadStrategy } from "./strategies/AliOSSUploadStrategy.uts";
import { AliUniUploadStrategy } from "./strategies/AliUniUploadStrategy.uts"; import { AliUniUploadStrategy } from "./strategies/AliUniUploadStrategy.uts";
import { UniUploadStrategy } from "./strategies/UniUploadStrategy.uts"; import { UniUploadStrategy } from "./strategies/UniUploadStrategy.uts";
import { UploadOptions, UploadResult, UploadStrategyType } from "./types/index.uts"; import { UploadOptions, UploadResult, UploadStrategyType } from "./types/index.uts";
import { IUploadStrategy } from "./types/IUploadStrategy.uts"; import { IUploadStrategy } from "./types/IUploadStrategy.uts";
const logger = Logger.getInstance();
/** /**
* 文件上传服务 * 文件上传服务
* 提供通用的文件上传能力,支持策略切换 * 提供通用的文件上传能力,支持策略切换
...@@ -38,26 +40,13 @@ class FileUploadService { ...@@ -38,26 +40,13 @@ class FileUploadService {
* @param type 策略类型 * @param type 策略类型
*/ */
setStrategy(type: UploadStrategyType) { setStrategy(type: UploadStrategyType) {
switch (type) { const next = this.createStrategy(type);
case UploadStrategyType.ALI_OSS: { if (next == null) {
this.strategy = new AliOSSUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: AliOSS (Native SDK)`, "FileUploadService");
break;
}
case UploadStrategyType.ALI_UNI: {
this.strategy = new AliUniUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: AliUni (uni.uploadFile -> OSS)`, "FileUploadService");
break;
}
case UploadStrategyType.UNI_UPLOAD: {
this.strategy = new UniUploadStrategy();
logger.info(`[FileUploadService] 切换策略为: uni.uploadFile (Generic)`, "FileUploadService");
break;
}
default: {
logger.warn(`[FileUploadService] 未知策略: ${type}, 保持当前策略`, "FileUploadService"); logger.warn(`[FileUploadService] 未知策略: ${type}, 保持当前策略`, "FileUploadService");
return;
} }
} this.strategy = next;
logger.info(`[FileUploadService] 切换策略为: ${type}`, "FileUploadService");
} }
/** /**
...@@ -65,9 +54,33 @@ class FileUploadService { ...@@ -65,9 +54,33 @@ class FileUploadService {
* @param options 配置对象 * @param options 配置对象
* @returns Promise<UploadResult> 返回上传结果 * @returns Promise<UploadResult> 返回上传结果
*/ */
async upload(options: UploadOptions): Promise<UploadResult> { async upload(options: UploadOptions, type: null | UploadStrategyType = null): Promise<UploadResult> {
if (type == null) {
return this.strategy.upload(options); return this.strategy.upload(options);
} }
const target = this.createStrategy(type);
if (target == null) {
throw new Error(`unknown upload strategy: ${type}`);
}
return target.upload(options);
}
private createStrategy(type: UploadStrategyType): IUploadStrategy | null {
switch (type) {
case UploadStrategyType.ALI_OSS: {
return new AliOSSUploadStrategy();
}
case UploadStrategyType.ALI_UNI: {
return new AliUniUploadStrategy();
}
case UploadStrategyType.UNI_UPLOAD: {
return new UniUploadStrategy();
}
default: {
return null;
}
}
}
} }
export default FileUploadService.getInstance(); export default FileUploadService.getInstance();
...@@ -3,9 +3,11 @@ import type { OssTokenData } from "../types/oss.uts"; ...@@ -3,9 +3,11 @@ 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 { OSS_CONFIG } from "@/config/oss.config.uts";
import { logger } from "../../logger/index.uts"; import { Logger } from "../../logger/LoggerCore.uts";
import { IUploadStrategy } from "../types/IUploadStrategy.uts";
import { UploadOptions, UploadResult } from "../types/index.uts"; import { UploadOptions, UploadResult } from "../types/index.uts";
import { IUploadStrategy } from "../types/IUploadStrategy.uts";
const logger = Logger.getInstance();
/** /**
* 阿里云 OSS 上传策略基类 * 阿里云 OSS 上传策略基类
......
import type { OssTokenData } from "../types/oss.uts"; import type { OssTokenData } from "../types/oss.uts";
import { logger } from "../../logger/index.uts"; import { Logger } from "../../logger/LoggerCore.uts";
import { UploadOptions, UploadResult } from "../types/index.uts"; import { UploadOptions, UploadResult } from "../types/index.uts";
import { base64Encode, hmacSha1 } from "../utils/PureCrypto.uts"; import { base64Encode, hmacSha1 } from "../utils/PureCrypto.uts";
import { AliOSSBaseStrategy } from "./AliOSSBaseStrategy.uts"; import { AliOSSBaseStrategy } from "./AliOSSBaseStrategy.uts";
const logger = Logger.getInstance();
/** /**
* 阿里云 OSS 上传策略 (使用 uni.uploadFile) * 阿里云 OSS 上传策略 (使用 uni.uploadFile)
* 替代原生 SDK 方案,避免兼容性问题 * 替代原生 SDK 方案,避免兼容性问题
......
...@@ -16,20 +16,21 @@ export class UniUploadStrategy implements IUploadStrategy { ...@@ -16,20 +16,21 @@ export class UniUploadStrategy implements IUploadStrategy {
if (uploadUrl === null || uploadUrl === "") { if (uploadUrl === null || uploadUrl === "") {
throw new Error("uploadUrl is required for UniUploadStrategy"); throw new Error("uploadUrl is required for UniUploadStrategy");
} }
const formDataValue = options.formData;
const headerValue = options.header;
const formData = formDataValue !== null && typeof formDataValue === "object" ? formDataValue as UTSJSONObject : {} as UTSJSONObject;
const header = headerValue !== null && typeof headerValue === "object" ? headerValue as UTSJSONObject : {} as UTSJSONObject;
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<UploadResult>((resolve, reject) => {
uni.uploadFile({ uni.uploadFile({
url: uploadUrl, url: uploadUrl,
filePath, filePath,
name: options.getString("name") ?? "file", name: "file",
formData: options.formData as UTSJSONObject, formData,
header: options.header as UTSJSONObject, // header,
timeout:300_000,
success: (res) => { success: (res) => {
logger.info(`[UniUploadStrategy] 上传成功: ${res.statusCode}`, "FileUploadService");
let data: UploadResult; let data: UploadResult;
try { try {
if (typeof res.data === "string") { if (typeof res.data === "string") {
...@@ -38,19 +39,24 @@ export class UniUploadStrategy implements IUploadStrategy { ...@@ -38,19 +39,24 @@ export class UniUploadStrategy implements IUploadStrategy {
data = res.data as UploadResult; data = res.data as UploadResult;
} }
} catch { } catch {
data = { rawData: res.data }; const fallback = { rawData: res.data };
data = JSON.parse(JSON.stringify(fallback)) as UploadResult;
} }
// 统一返回结构,尽量包含 url 字段如果服务端返回了
// 这里假设服务端返回的数据中可能包含 url,或者直接返回整个 data
data.strategy = "uni"; data.strategy = "uni";
data.statusCode = res.statusCode; data.statusCode = res.statusCode;
if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(data); resolve(data);
} else {
logger.error(`[UniUploadStrategy] 服务端返回错误: ${res.statusCode}`, "FileUploadService");
reject(new Error(`Upload failed with status ${res.statusCode}`));
}
}, },
fail: (err) => { fail: (err: any) => {
logger.error(`[UniUploadStrategy] 上传失败: ${err.errMsg}`, "FileUploadService"); logger.error(`[UniUploadStrategy] 上传失败: ${err}`, "FileUploadService");
reject(new Error(err.errMsg)); const errorMsg = JSON.stringify(err);
reject(new Error(errorMsg));
} }
}); });
}); });
......
...@@ -529,7 +529,6 @@ export function debounce(func: () => void, delay: number): () => number { ...@@ -529,7 +529,6 @@ export function debounce(func: () => void, delay: number): () => number {
} }
// 设置新的定时器 // 设置新的定时器
// @ts-ignore
timeoutId = setTimeout(() => { timeoutId = setTimeout(() => {
func(); func();
timeoutId = 0; timeoutId = 0;
......
/* eslint-disable unicorn/text-encoding-identifier-case */
/** /**
* plus.io 的 uni-app x 替代实现 * plus.io 的 uni-app x 替代实现
* 用于文件系统操作 * 用于文件系统操作
...@@ -60,8 +61,8 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise< ...@@ -60,8 +61,8 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.readFile({ fs.readFile({
filePath: filePath, filePath,
encoding: encoding, encoding,
success: (res: any) => { success: (res: any) => {
// ReadFileSuccessResult 类型,data 类型为 string | ArrayBuffer // ReadFileSuccessResult 类型,data 类型为 string | ArrayBuffer
// 由于 ReadFileSuccessResult 不是 UTSJSONObject,需要特殊处理 // 由于 ReadFileSuccessResult 不是 UTSJSONObject,需要特殊处理
...@@ -72,15 +73,13 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise< ...@@ -72,15 +73,13 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
try { try {
const jsonStr = JSON.stringify(res); const jsonStr = JSON.stringify(res);
// @ts-ignore
const parsed = JSON.parseObject(jsonStr); const parsed = JSON.parseObject(jsonStr);
if (parsed != null) { if (parsed != null) {
const temp = parsed.getAny("data"); const temp = parsed.getAny("data");
console.error("readFile getAny('data'): ", temp);
raw = temp != null ? temp as any : null; raw = temp != null ? temp as any : null;
} }
} catch (e: any) { } catch {
// 方法2:如果 parseObject 失败,尝试用普通 parse // 方法2:如果 parseObject 失败,尝试用普通 parse
try { try {
...@@ -90,16 +89,15 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise< ...@@ -90,16 +89,15 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// 尝试从解析后的对象中获取 data // 尝试从解析后的对象中获取 data
if (parsed != null) { if (parsed != null) {
const temp = get(parsed as UTSJSONObject, "data"); const temp = get(parsed as UTSJSONObject, "data");
console.error("readFile get('data'): ", temp);
raw = temp != null ? temp as any : null; raw = temp != null ? temp as any : null;
} }
} catch (e2: any) { } catch (error: any) {
console.error("readFile method2 failed: ", e2); console.error("readFile method2 failed:", error);
} }
} }
if (raw != null) { if (raw != null) {
if (typeof raw == "string") { if (typeof raw === "string") {
text = raw as string; text = raw as string;
} else { } else {
// ArrayBuffer 类型,需要转换为字符串 // ArrayBuffer 类型,需要转换为字符串
...@@ -107,11 +105,10 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise< ...@@ -107,11 +105,10 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// App 端:ArrayBuffer 转字符串 // App 端:ArrayBuffer 转字符串
// 对于 utf-8 编码,可以直接使用 TextDecoder // 对于 utf-8 编码,可以直接使用 TextDecoder
try { try {
// @ts-ignore
const decoder = new TextDecoder("utf-8"); const decoder = new TextDecoder("utf-8");
text = decoder.decode(raw as ArrayBuffer); text = decoder.decode(raw as ArrayBuffer);
} catch (e: any) { } catch (error: any) {
console.error("ArrayBuffer decode error: ", e); console.error("ArrayBuffer decode error:", error);
text = ""; text = "";
} }
// #endif // #endif
...@@ -121,11 +118,10 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise< ...@@ -121,11 +118,10 @@ export function readFile(filePath: string, encoding: string = "utf-8"): Promise<
// #endif // #endif
} }
} }
console.error("readFile text final: ", text);
resolve(text); resolve(text);
}, },
fail: (err: any) => { fail: (err: any) => {
console.error("readFile fail: ", err); console.error("readFile fail:", err);
reject(err); reject(err);
} }
}); });
...@@ -141,8 +137,8 @@ export function writeFile(filePath: string, data: string): Promise<void> { ...@@ -141,8 +137,8 @@ export function writeFile(filePath: string, data: string): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.writeFile({ fs.writeFile({
filePath: filePath, filePath,
data: data, data,
encoding: "utf-8", encoding: "utf-8",
success: () => { success: () => {
resolve(); resolve();
...@@ -162,7 +158,7 @@ export function deleteFile(filePath: string): Promise<void> { ...@@ -162,7 +158,7 @@ export function deleteFile(filePath: string): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.unlink({ fs.unlink({
filePath: filePath, filePath,
success: () => { success: () => {
resolve(); resolve();
}, },
...@@ -181,14 +177,25 @@ export function readDirectory(dirPath: string): Promise<string[]> { ...@@ -181,14 +177,25 @@ export function readDirectory(dirPath: string): Promise<string[]> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.readdir({ fs.readdir({
dirPath: dirPath, dirPath,
success: (res: any) => { success: (res: any) => {
const files = res.files; let fileList: any | null = null;
if (files instanceof Array) { try {
resolve(files as string[]); const jsonStr = JSON.stringify(res);
} else { const parsed = JSON.parseObject(jsonStr);
resolve([]); if (parsed != null) {
fileList = parsed.getAny("files");
}
} catch {
try {
const jsonStr = JSON.stringify(res);
const parsed = JSON.parse(jsonStr);
if (parsed != null) {
fileList = get(parsed as UTSJSONObject, "files");
}
} catch {}
} }
resolve(Array.isArray(fileList) ? fileList as string[] : []);
}, },
fail: (err: any) => { fail: (err: any) => {
reject(err); reject(err);
...@@ -206,8 +213,8 @@ export function createDirectory(dirPath: string, recursive: boolean = false): Pr ...@@ -206,8 +213,8 @@ export function createDirectory(dirPath: string, recursive: boolean = false): Pr
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.mkdir({ fs.mkdir({
dirPath: dirPath, dirPath,
recursive: recursive, recursive,
success: () => { success: () => {
resolve(); resolve();
}, },
...@@ -227,8 +234,8 @@ export function deleteDirectory(dirPath: string, recursive: boolean = false): Pr ...@@ -227,8 +234,8 @@ export function deleteDirectory(dirPath: string, recursive: boolean = false): Pr
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fs = uni.getFileSystemManager(); const fs = uni.getFileSystemManager();
fs.rmdir({ fs.rmdir({
dirPath: dirPath, dirPath,
recursive: recursive, recursive,
success: () => { success: () => {
resolve(); resolve();
}, },
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!