feat: images upload

This commit is contained in:
Ivan Rezchikov
2026-07-04 15:45:05 +03:00
parent 2eb0de5357
commit e192717466
38 changed files with 1334 additions and 615 deletions
+61
View File
@@ -0,0 +1,61 @@
import crypto from "crypto";
import sharp from "sharp";
import { AppError } from "@/lib/action-result";
import { minioClient } from "@/lib/minio";
const BUCKET = "uploads";
const MAX_FILE_SIZE = 5 * 1024 * 1024;
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");
}
const input = Buffer.from(await file.arrayBuffer());
let image = sharp(input, {
failOn: "error",
});
const metadata = await image.metadata();
if (!metadata.format) {
throw new AppError("Only JPEG, PNG, or WEBP images are allowed");
}
const output = await image
.rotate()
.webp({
quality: 80,
effort: 4,
})
.toBuffer();
const key = `${directory}/${crypto.randomUUID()}.webp`;
await minioClient.putObject(
BUCKET,
key,
output,
output.length,
{
"Content-Type": "image/webp",
},
);
return key;
}
export async function getImageUrl(key: string): Promise<string> {
return minioClient.presignedGetObject(
BUCKET,
key,
60 * 5
);
}