⚗️ add minio lib
add minio lib for storing file in file system as bucket storage
This commit is contained in:
14
src/utils/storages/MinIO/client.ts
Normal file
14
src/utils/storages/MinIO/client.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { Client } from "minio";
|
||||
|
||||
const useSSL = false;
|
||||
|
||||
export const minioClient = new Client({
|
||||
endPoint: process.env.MINIO_HOST!,
|
||||
port: parseInt(process.env.MINIO_PORT!),
|
||||
accessKey: process.env.MINIO_ACCESS_KEY!,
|
||||
secretKey: process.env.MINIO_SECRET_KEY!,
|
||||
useSSL,
|
||||
});
|
||||
|
||||
export const minioBucketName = process.env.MINIO_BUCKET!;
|
||||
export const minioProtocol = useSSL ? "https" : "http";
|
||||
29
src/utils/storages/MinIO/operations/uploadFile.ts
Normal file
29
src/utils/storages/MinIO/operations/uploadFile.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { minioBucketName, minioClient, minioProtocol } from "../client";
|
||||
import { ensureBucketExists } from "../validations/ensureBucketExists";
|
||||
import { Readable } from "stream";
|
||||
|
||||
export const uploadFile = async (
|
||||
file: File,
|
||||
options?: {
|
||||
fileDir?: string;
|
||||
fileName?: string;
|
||||
}
|
||||
): Promise<string> => {
|
||||
// Ensure the target MinIO bucket exists before performing any upload
|
||||
await ensureBucketExists();
|
||||
|
||||
// Convert the uploaded file into a readable stream using ArrayBuffer and Node.js Buffer for further processing
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
const stream = Readable.from(buffer);
|
||||
|
||||
// Define the target file path using optional directory and filename; generate UUID if filename is not provided and preserve original file extension
|
||||
const fileDir = options?.fileDir ?? "";
|
||||
const fileName = options?.fileName ?? crypto.randomUUID();
|
||||
const fileExt = file.name.split(".").pop();
|
||||
const pathDir = `${fileDir}/${fileName}.${fileExt}`;
|
||||
|
||||
// Upload the file stream to the specified MinIO bucket and path
|
||||
await minioClient.putObject(minioBucketName, pathDir, stream);
|
||||
return pathDir;
|
||||
};
|
||||
@ -0,0 +1,9 @@
|
||||
import { AppError } from "../../../../helpers/error/instances/app";
|
||||
import { minioBucketName, minioClient } from "../client";
|
||||
|
||||
export const ensureBucketExists = async () => {
|
||||
const exists = await minioClient.bucketExists(minioBucketName);
|
||||
if (!exists) {
|
||||
throw new AppError(503, "MinIO bucket is not configured properly");
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user