feat(api): StorageService 支持 MINIO_PUBLIC_URL 配置

- 添加 publicUrl 配置支持外部访问地址
- getPresignedUrl 方法自动替换内部地址为公开地址
- 移除已迁移到 file 模块的路径前缀常量

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
charilezhou
2026-01-19 13:47:36 +08:00
parent 2914d1e090
commit 76f835a2ad
2 changed files with 24 additions and 12 deletions

View File

@@ -14,11 +14,3 @@ export const GLOBAL_ALLOWED_TYPES = [
// 全局最大文件大小10MB
export const GLOBAL_MAX_FILE_SIZE = 10 * 1024 * 1024;
// ============ 存储路径前缀 ============
// 头像存储路径前缀
export const AVATAR_PREFIX = 'avatars';
// 附件存储路径前缀
export const ATTACHMENT_PREFIX = 'attachments';

View File

@@ -8,16 +8,25 @@ export class StorageService implements OnModuleInit {
private readonly logger = new Logger(StorageService.name);
private client: Minio.Client;
private bucket: string;
private publicUrl: string | null;
constructor(private configService: ConfigService) {
const endpoint = this.configService.get('MINIO_ENDPOINT', 'localhost');
const port = parseInt(this.configService.get('MINIO_PORT', '9000'), 10);
const useSSL = this.configService.get('MINIO_USE_SSL', 'false') === 'true';
this.client = new Minio.Client({
endPoint: this.configService.get('MINIO_ENDPOINT', 'localhost'),
port: parseInt(this.configService.get('MINIO_PORT', '9000'), 10),
useSSL: this.configService.get('MINIO_USE_SSL', 'false') === 'true',
endPoint: endpoint,
port,
useSSL,
accessKey: this.configService.get('MINIO_ACCESS_KEY', 'minioadmin'),
secretKey: this.configService.get('MINIO_SECRET_KEY', 'minioadmin'),
});
this.bucket = this.configService.get('MINIO_BUCKET', 'seclusion');
// 公开访问 URL用于替换 presigned URL 中的内部地址)
const publicUrlConfig = this.configService.get<string>('MINIO_PUBLIC_URL');
this.publicUrl = publicUrlConfig?.trim() || null;
}
async onModuleInit() {
@@ -63,6 +72,17 @@ export class StorageService implements OnModuleInit {
* @param expiresIn 有效期(秒)
*/
async getPresignedUrl(objectName: string, expiresIn: number): Promise<string> {
return this.client.presignedGetObject(this.bucket, objectName, expiresIn);
const url = await this.client.presignedGetObject(this.bucket, objectName, expiresIn);
// 如果配置了公开访问 URL替换内部地址
if (this.publicUrl) {
const urlObj = new URL(url);
const publicUrlObj = new URL(this.publicUrl);
urlObj.protocol = publicUrlObj.protocol;
urlObj.host = publicUrlObj.host;
return urlObj.toString();
}
return url;
}
}