This commit is contained in:
Ivan Rezchikov
2026-07-11 21:20:57 +03:00
parent e192717466
commit 18161f4604
57 changed files with 1211 additions and 615 deletions
+21 -25
View File
@@ -5,53 +5,49 @@ import { AppError } from "@/lib/action-result";
import { minioClient } from "@/lib/minio";
const BUCKET = "uploads";
const MAX_FILE_SIZE = 5 * 1024 * 1024;
const ALLOWED_INPUT_FORMATS = new Set(["jpeg", "png", "webp"]);
export async function uploadImage(file: File, directory: string): Promise<string> {
if (file.size === 0) {
throw new AppError("A file is required");
}
if (file.size > MAX_FILE_SIZE) {
throw new AppError("Image must be smaller than 5MB");
}
export async function uploadImage(file: File, directory: string, options: { maxWidth: number; maxHeight: number; fit?: "inside" | "cover"; removeBg?: boolean }): Promise<string> {
if (file.size === 0) throw new AppError("A file is required");
if (file.size > MAX_FILE_SIZE) throw new AppError("Image must be smaller than 5MB");
const input = Buffer.from(await file.arrayBuffer());
let image = sharp(input, {
failOn: "error",
limitInputPixels: 30_000_000,
});
const metadata = await image.metadata();
if (!metadata.format) {
if (!metadata.format || !ALLOWED_INPUT_FORMATS.has(metadata.format)) {
throw new AppError("Only JPEG, PNG, or WEBP images are allowed");
}
if (!metadata.width || !metadata.height || metadata.width < 100 || metadata.height < 100) {
throw new AppError("Image is too small");
}
const output = await image
.rotate()
.webp({
quality: 80,
effort: 4,
.resize({
width: options.maxWidth,
height: options.maxHeight,
fit: options.fit ?? "inside",
withoutEnlargement: true,
})
.webp({ quality: 80, effort: 4 })
.toBuffer();
const key = `${directory}/${crypto.randomUUID()}.webp`;
await minioClient.putObject(
BUCKET,
key,
output,
output.length,
{
"Content-Type": "image/webp",
},
);
await minioClient.putObject(BUCKET, key, output, output.length, { "Content-Type": "image/webp" });
return key;
}
export async function removeImage(key: string) {
await minioClient.removeObject(BUCKET, key)
}
export async function getImageUrl(key: string): Promise<string> {
return minioClient.presignedGetObject(
BUCKET,