Minioストレージを共通化する

This commit is contained in:
ry.yamafuji 2025-03-22 14:22:41 +09:00
parent 2454db7d13
commit a023dacbc0
2 changed files with 74 additions and 2 deletions

View File

@ -3,6 +3,8 @@
// 型定義をインポート
const Minio = require('minio');
// enum を使っている場合
const { ProcessType } = require('../types/IStorage');
const fs = require('fs');
@ -38,6 +40,76 @@ class MinioStorage {
throw err;
});
}
/**
* オブジェクトをファイルとして保存ローカル
* @param {string} objectKey 取得するオブジェクトキー
* @param {string} destinationPath 保存先ファイルパス
* @returns {Promise<void>}
*/
async downloadFile(objectKey, destinationPath) {
const dataStream = await this.minioClient.getObject(this.bucketName, objectKey);
return new Promise((resolve, reject) => {
const fileStream = fs.createWriteStream(destinationPath);
dataStream.pipe(fileStream);
dataStream.on('end', () => {
console.log('File Download File end');
resolve();
});
dataStream.on('error', reject);
});
}
/**
* オブジェクトをメモリ上に読み込む(Buffer)
* @param {string} objectKey 取得するオブジェクトキー
* @returns {Promise<Buffer>}
*/
async downloadContents(objectKey) {
const dataStream = await this.minioClient.getObject(this.bucketName, objectKey);
return new Promise((resolve, reject) => {
const chunks = [];
dataStream.on('data', chunk => chunks.push(chunk));
dataStream.on('end', () => resolve(Buffer.concat(chunks)));
dataStream.on('error', reject);
});
}
/**
* 単一オブジェクトを削除する
* @param {string} objectKey 削除するオブジェクトキー
* @returns {Promise<void>}
*/
async delete(objectKey) {
await this.minioClient.removeObject(this.bucketName, objectKey);
console.log('File deleted successfully.');
}
/**
* 署名付きURLを生成するGET or PUT
* @param {string} objectKey 対象のオブジェクトキー
* @param {number} processType 処理タイプ0=GET, 1=PUT
* @param {{ expiresIn: number }} options 有効期限
* @returns {Promise<string>} 発行された署名付きURL
*/
async getSignedUrl(objectKey, processType, options) {
if (!options.expiresIn) {
options.expiresIn = 60 * 60; // 1 hours
}
switch (processType) {
case ProcessType.GET:
return this.minioClient.presignedGetObject(this.bucketName, objectKey, options.expiresIn);
case ProcessType.PUT:
return this.minioClient.presignedPutObject(this.bucketName, objectKey, options.expiresIn);
default:
throw new Error('Invalid process type.');
}
}
}
module.exports = MinioStorage;

View File

@ -32,7 +32,7 @@ export interface IStorage {
* @param destinationPath
* @returns Buffer
*/
download(objectKey: string, destinationPath: string): Promise<void>;
downloadFile(objectKey: string, destinationPath: string): Promise<void>;
/**
*