feat: 优化静态资源缓存策略
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { createHash } from 'crypto';
|
||||
import dayjs from 'dayjs';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { extname } from 'path';
|
||||
import { LocalDriver } from './local.driver';
|
||||
import { OssDriver } from './oss.driver';
|
||||
import { SavedFile, StorageDriver } from './storage.types';
|
||||
|
||||
export const STATIC_ASSET_CACHE_CONTROL = 'public, max-age=31536000, immutable';
|
||||
|
||||
const MIME_EXT: Record<string, string> = {
|
||||
'image/jpeg': '.jpg',
|
||||
'image/png': '.png',
|
||||
'image/webp': '.webp',
|
||||
'image/gif': '.gif',
|
||||
'image/svg+xml': '.svg',
|
||||
'video/mp4': '.mp4',
|
||||
'video/webm': '.webm',
|
||||
'video/quicktime': '.mov',
|
||||
'application/pdf': '.pdf',
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class StorageService {
|
||||
private readonly logger = new Logger(StorageService.name);
|
||||
private readonly driver: StorageDriver;
|
||||
|
||||
constructor(private readonly config: ConfigService) {
|
||||
const s = this.config.get<Record<string, any>>('storage')!;
|
||||
if (s.driver === 'oss') {
|
||||
this.driver = new OssDriver({
|
||||
endpoint: s.oss.endpoint,
|
||||
region: s.oss.region,
|
||||
bucket: s.oss.bucket,
|
||||
accessKeyId: s.oss.accessKeyId,
|
||||
accessKeySecret: s.oss.accessKeySecret,
|
||||
cdnBaseUrl: s.cdnBaseUrl,
|
||||
});
|
||||
this.logger.log('存储驱动:OSS/S3 兼容');
|
||||
} else {
|
||||
this.driver = new LocalDriver({
|
||||
localDir: s.localDir,
|
||||
publicPrefix: s.publicPrefix,
|
||||
cdnBaseUrl: s.cdnBaseUrl,
|
||||
baseUrl: this.config.get<string>('baseUrl') || 'http://localhost:3000',
|
||||
});
|
||||
this.logger.log('存储驱动:本地磁盘');
|
||||
}
|
||||
}
|
||||
|
||||
private buildHash(buffer: Buffer): string {
|
||||
return createHash('sha256').update(buffer).digest('hex');
|
||||
}
|
||||
|
||||
private buildKey(originalName: string, hash: string, mime?: string): string {
|
||||
const ext = (mime && MIME_EXT[mime]) || extname(originalName) || '';
|
||||
return `${dayjs().format('YYYY/MM/DD')}/${hash.slice(0, 16)}-${nanoid()}${ext}`;
|
||||
}
|
||||
|
||||
async save(buffer: Buffer, originalName: string, mime?: string): Promise<SavedFile> {
|
||||
const hash = this.buildHash(buffer);
|
||||
const key = this.buildKey(originalName, hash, mime);
|
||||
await this.driver.put(key, buffer, {
|
||||
contentType: mime,
|
||||
cacheControl: STATIC_ASSET_CACHE_CONTROL,
|
||||
});
|
||||
return {
|
||||
key,
|
||||
url: this.driver.getPublicUrl(key),
|
||||
name: originalName,
|
||||
size: buffer.length,
|
||||
mime: mime || 'application/octet-stream',
|
||||
hash,
|
||||
};
|
||||
}
|
||||
|
||||
async putKey(key: string, buffer: Buffer, mime?: string): Promise<string> {
|
||||
await this.driver.put(key, buffer, {
|
||||
contentType: mime,
|
||||
cacheControl: STATIC_ASSET_CACHE_CONTROL,
|
||||
});
|
||||
return this.driver.getPublicUrl(key);
|
||||
}
|
||||
|
||||
derivedKey(sourceKey: string, suffix: string): string {
|
||||
const ext = extname(sourceKey);
|
||||
const base = sourceKey.slice(0, sourceKey.length - ext.length);
|
||||
return `${base}_${suffix}${ext || '.jpg'}`;
|
||||
}
|
||||
|
||||
getUrl(key: string): string {
|
||||
return this.driver.getPublicUrl(key);
|
||||
}
|
||||
|
||||
read(key: string): Promise<Buffer> {
|
||||
return this.driver.get(key);
|
||||
}
|
||||
|
||||
async remove(key: string): Promise<void> {
|
||||
await this.driver.remove(key);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user