feat: 优化静态资源缓存策略
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import {
|
||||
DeleteObjectCommand,
|
||||
GetObjectCommand,
|
||||
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 }));
|
||||
}
|
||||
|
||||
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}`;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user