⚗️ add minio lib

add minio lib for storing file in file system as bucket storage
This commit is contained in:
Rafi Arrafif
2025-07-21 15:21:37 +07:00
parent a6571461db
commit 945caca728
7 changed files with 108 additions and 12 deletions

View File

@ -11,7 +11,12 @@ export const createUserRoleWithAdminController = async (ctx: Context) => {
...body,
createdBy: "787",
});
return returnWriteResponse(ctx.set, 201, "User role created successfully");
return returnWriteResponse(
ctx.set,
201,
"User role created successfully",
createUserRole
);
} catch (error) {
return mainErrorHandler(ctx.set, error);
}

View 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";

View 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;
};

View File

@ -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");
}
};