feat: 优化静态资源缓存策略

This commit is contained in:
Nixevol
2026-07-05 22:01:48 +08:00
parent cb202825a3
commit 3efc1ecd88
11 changed files with 265 additions and 3 deletions
+8
View File
@@ -10,6 +10,7 @@ import { AppModule } from './app.module';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { OperationLogInterceptor } from './operation-log/operation-log.interceptor';
import { STATIC_ASSET_CACHE_CONTROL } from './storage/storage.service';
// 让 BigInt 可被 JSON 序列化为字符串,避免精度问题。
(BigInt.prototype as unknown as { toJSON: () => string }).toJSON = function () {
@@ -54,6 +55,13 @@ async function bootstrap(): Promise<void> {
}
app.useStaticAssets(localDir, {
prefix: config.get<string>('storage.publicPrefix') || '/uploads',
etag: true,
lastModified: true,
maxAge: '1y',
immutable: true,
setHeaders: (res) => {
res.setHeader('Cache-Control', STATIC_ASSET_CACHE_CONTROL);
},
});
// Swagger(开发文档)
+52
View File
@@ -0,0 +1,52 @@
import { existsSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'fs';
import { dirname, relative, resolve } from 'path';
import { PutOptions, StorageDriver } from './storage.types';
export interface LocalDriverOptions {
localDir: string;
publicPrefix: string;
cdnBaseUrl: string;
baseUrl: string;
}
// 本地磁盘存储驱动(默认)。文件经 Nest 静态目录对外访问。
export class LocalDriver implements StorageDriver {
private readonly root: string;
constructor(private readonly opts: LocalDriverOptions) {
this.root = resolve(opts.localDir);
}
private fullPath(key: string): string {
const full = resolve(this.root, key);
const rel = relative(this.root, full);
if (rel.startsWith('..') || rel === '' || rel.includes('..\\') || rel.includes('../')) {
throw new Error('Unsafe storage key');
}
return full;
}
async put(key: string, buffer: Buffer, _options?: PutOptions): Promise<void> {
const full = this.fullPath(key);
mkdirSync(dirname(full), { recursive: true });
writeFileSync(full, buffer);
}
async get(key: string): Promise<Buffer> {
return readFileSync(this.fullPath(key));
}
async remove(key: string): Promise<void> {
const full = this.fullPath(key);
if (existsSync(full)) {
rmSync(full, { force: true });
}
}
getPublicUrl(key: string): string {
if (this.opts.cdnBaseUrl) {
return `${this.opts.cdnBaseUrl.replace(/\/$/, '')}/${key}`;
}
return `${this.opts.baseUrl.replace(/\/$/, '')}${this.opts.publicPrefix}/${key}`;
}
}
+66
View File
@@ -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}`;
}
}
+9
View File
@@ -0,0 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { StorageService } from './storage.service';
@Global()
@Module({
providers: [StorageService],
exports: [StorageService],
})
export class StorageModule {}
+104
View File
@@ -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);
}
}
+20
View File
@@ -0,0 +1,20 @@
export interface PutOptions {
contentType?: string;
cacheControl?: string;
}
export interface StorageDriver {
put(key: string, buffer: Buffer, options?: PutOptions): Promise<void>;
get(key: string): Promise<Buffer>;
remove(key: string): Promise<void>;
getPublicUrl(key: string): string;
}
export interface SavedFile {
key: string;
url: string;
name: string;
size: number;
mime: string;
hash: string;
}