81 lines
2.3 KiB
TypeScript
81 lines
2.3 KiB
TypeScript
import {
|
|
DeleteObjectCommand,
|
|
GetObjectCommand,
|
|
ListObjectsV2Command,
|
|
PutObjectCommand,
|
|
S3Client,
|
|
} from '@aws-sdk/client-s3';
|
|
import { PutOptions, StorageDriver } from './storage.types';
|
|
|
|
export interface OssDriverOptions {
|
|
endpoint: string;
|
|
region: string;
|
|
bucket: string;
|
|
accessKeyId: string;
|
|
accessKeySecret: string;
|
|
cdnBaseUrl: string;
|
|
}
|
|
|
|
// S3 兼容对象存储驱动(阿里云 OSS S3 兼容端点 / MinIO 等通用)。
|
|
// 仅在 STORAGE_DRIVER=oss 时启用;凭据在 .env 配置,业务代码无需改动即可切换。
|
|
export class OssDriver implements StorageDriver {
|
|
private readonly client: S3Client;
|
|
|
|
constructor(private readonly opts: OssDriverOptions) {
|
|
this.client = new S3Client({
|
|
region: opts.region || 'us-east-1',
|
|
endpoint: opts.endpoint || undefined,
|
|
forcePathStyle: true,
|
|
credentials: {
|
|
accessKeyId: opts.accessKeyId,
|
|
secretAccessKey: opts.accessKeySecret,
|
|
},
|
|
});
|
|
}
|
|
|
|
async put(key: string, buffer: Buffer, options?: PutOptions): Promise<void> {
|
|
await this.client.send(
|
|
new PutObjectCommand({
|
|
Bucket: this.opts.bucket,
|
|
Key: key,
|
|
Body: buffer,
|
|
ContentType: options?.contentType,
|
|
CacheControl: options?.cacheControl,
|
|
}),
|
|
);
|
|
}
|
|
|
|
async get(key: string): Promise<Buffer> {
|
|
const res = await this.client.send(
|
|
new GetObjectCommand({ Bucket: this.opts.bucket, Key: key }),
|
|
);
|
|
const bytes = await res.Body!.transformToByteArray();
|
|
return Buffer.from(bytes);
|
|
}
|
|
|
|
async remove(key: string): Promise<void> {
|
|
await this.client.send(new DeleteObjectCommand({ Bucket: this.opts.bucket, Key: key }));
|
|
}
|
|
|
|
async list(): Promise<string[]> {
|
|
const keys: string[] = [];
|
|
let token: string | undefined;
|
|
do {
|
|
const res = await this.client.send(new ListObjectsV2Command({ Bucket: this.opts.bucket, ContinuationToken: token }));
|
|
for (const item of res.Contents || []) {
|
|
if (item.Key) keys.push(item.Key);
|
|
}
|
|
token = res.NextContinuationToken;
|
|
} while (token);
|
|
return keys;
|
|
}
|
|
|
|
getPublicUrl(key: string): string {
|
|
if (this.opts.cdnBaseUrl) {
|
|
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
|
|
}
|
|
const base = (this.opts.endpoint || '').replace(/\/$/, '');
|
|
return `${base}/${this.opts.bucket}/${key}`;
|
|
}
|
|
}
|