Files
certd/packages/plugins/plugin-lib/src/oss/api.ts

91 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-04-25 01:26:04 +08:00
import { IAccessService } from "@certd/pipeline";
import { ILogger, utils } from "@certd/basic";
import dayjs from "dayjs";
export type OssClientRemoveByOpts = {
dir?: string;
//删除多少天前的文件
2025-04-24 17:27:13 +08:00
beforeDays?: number;
};
2025-04-25 01:26:04 +08:00
export type OssFileItem = {
2025-04-27 01:31:46 +08:00
//文件全路径
2025-04-25 01:26:04 +08:00
path: string;
size: number;
//毫秒时间戳
lastModified: number;
};
export type IOssClient = {
upload: (fileName: string, fileContent: Buffer) => Promise<void>;
remove: (fileName: string, opts?: { joinRootDir?: boolean }) => Promise<void>;
2025-04-25 01:26:04 +08:00
download: (fileName: string, savePath: string) => Promise<void>;
removeBy: (removeByOpts: OssClientRemoveByOpts) => Promise<void>;
listDir: (dir: string) => Promise<OssFileItem[]>;
};
export type OssClientContext = {
accessService: IAccessService;
logger: ILogger;
utils: typeof utils;
};
export abstract class BaseOssClient<A> implements IOssClient {
rootDir: string = "";
access: A = null;
logger: ILogger;
utils: typeof utils;
ctx: OssClientContext;
protected constructor(opts: { rootDir?: string; access: A }) {
this.rootDir = opts.rootDir || "";
this.access = opts.access;
}
join(...strs: string[]) {
let res = "";
for (const item of strs) {
if (item) {
if (!res) {
res = item;
} else {
res += "/" + item;
}
}
}
res = res.replace(/[\\/]+/g, "/");
return res;
}
async setCtx(ctx: any) {
// set context
this.ctx = ctx;
this.logger = ctx.logger;
this.utils = ctx.utils;
await this.init();
}
async init() {
// do nothing
}
2025-04-24 17:27:13 +08:00
2025-04-27 01:31:46 +08:00
abstract remove(fileName: string, opts?: { joinRootDir?: boolean }): Promise<void>;
2025-04-25 01:26:04 +08:00
abstract upload(fileName: string, fileContent: Buffer): Promise<void>;
abstract download(fileName: string, savePath: string): Promise<void>;
abstract listDir(dir: string): Promise<OssFileItem[]>;
2025-04-24 17:27:13 +08:00
2025-04-25 01:26:04 +08:00
async removeBy(removeByOpts: OssClientRemoveByOpts): Promise<void> {
const list = await this.listDir(removeByOpts.dir);
2025-04-27 01:31:46 +08:00
// removeByOpts.beforeDays = 0;
2025-04-25 01:26:04 +08:00
const beforeDate = dayjs().subtract(removeByOpts.beforeDays, "day");
for (const item of list) {
if (item.lastModified && item.lastModified < beforeDate.valueOf()) {
2025-04-27 01:31:46 +08:00
await this.remove(item.path, { joinRootDir: false });
2025-04-25 01:26:04 +08:00
}
}
}
2025-04-24 17:27:13 +08:00
}