商城后端模板
This commit is contained in:
97
config/minio.js
Normal file
97
config/minio.js
Normal file
@@ -0,0 +1,97 @@
|
||||
const Minio = require('minio');
|
||||
require('dotenv').config();
|
||||
|
||||
/**
|
||||
* MinIO 配置
|
||||
* 用于对象存储服务配置
|
||||
*/
|
||||
const minioConfig = {
|
||||
// MinIO 服务器配置
|
||||
endPoint: process.env.MINIO_ENDPOINT || 'localhost',
|
||||
port: parseInt(process.env.MINIO_PORT) || 9000,
|
||||
useSSL: process.env.MINIO_USE_SSL === 'true' || false,
|
||||
accessKey: process.env.MINIO_ACCESS_KEY || 'minioadmin',
|
||||
secretKey: process.env.MINIO_SECRET_KEY || 'minioadmin',
|
||||
|
||||
// 存储桶配置
|
||||
buckets: {
|
||||
uploads: process.env.MINIO_BUCKET_UPLOADS || 'uploads',
|
||||
avatars: process.env.MINIO_BUCKET_AVATARS || 'avatars',
|
||||
products: process.env.MINIO_BUCKET_PRODUCTS || 'products',
|
||||
documents: process.env.MINIO_BUCKET_DOCUMENTS || 'documents'
|
||||
},
|
||||
|
||||
// 文件访问配置
|
||||
publicUrl: process.env.MINIO_PUBLIC_URL || `http://localhost:9000`
|
||||
};
|
||||
|
||||
/**
|
||||
* 创建 MinIO 客户端实例
|
||||
*/
|
||||
const createMinioClient = () => {
|
||||
return new Minio.Client({
|
||||
endPoint: minioConfig.endPoint,
|
||||
port: minioConfig.port,
|
||||
useSSL: minioConfig.useSSL,
|
||||
accessKey: minioConfig.accessKey,
|
||||
secretKey: minioConfig.secretKey
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* 初始化存储桶
|
||||
* 确保所有需要的存储桶都存在
|
||||
*/
|
||||
const initializeBuckets = async () => {
|
||||
const minioClient = createMinioClient();
|
||||
|
||||
try {
|
||||
// 检查并创建存储桶
|
||||
for (const [key, bucketName] of Object.entries(minioConfig.buckets)) {
|
||||
const exists = await minioClient.bucketExists(bucketName);
|
||||
if (!exists) {
|
||||
await minioClient.makeBucket(bucketName, 'us-east-1');
|
||||
console.log(`✅ 存储桶 '${bucketName}' 创建成功`);
|
||||
|
||||
// 设置存储桶策略为公开读取(可选)
|
||||
const policy = {
|
||||
Version: '2012-10-17',
|
||||
Statement: [
|
||||
{
|
||||
Effect: 'Allow',
|
||||
Principal: { AWS: ['*'] },
|
||||
Action: ['s3:GetObject'],
|
||||
Resource: [`arn:aws:s3:::${bucketName}/*`]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
try {
|
||||
await minioClient.setBucketPolicy(bucketName, JSON.stringify(policy));
|
||||
console.log(`✅ 存储桶 '${bucketName}' 策略设置成功`);
|
||||
} catch (policyError) {
|
||||
console.warn(`⚠️ 存储桶 '${bucketName}' 策略设置失败:`, policyError.message);
|
||||
}
|
||||
} else {
|
||||
console.log(`✅ 存储桶 '${bucketName}' 已存在`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ 初始化存储桶失败:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取文件的公开访问URL
|
||||
*/
|
||||
const getPublicUrl = (bucketName, objectName) => {
|
||||
return `${minioConfig.publicUrl}/${bucketName}/${objectName}`;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
minioConfig,
|
||||
createMinioClient,
|
||||
initializeBuckets,
|
||||
getPublicUrl
|
||||
};
|
||||
Reference in New Issue
Block a user