upload photo controller fixed

This commit is contained in:
Saimon8420 2025-02-05 15:38:32 +06:00
parent 473a741f10
commit 0e49fc53ab

View file

@ -1,6 +1,6 @@
import { eq } from "drizzle-orm";
import { db } from "../../db";
import { uploads } from "../../db/schema";
import { projects, uploads } from "../../db/schema";
import { uploadToMinio } from "../../helper/upload/uploadToMinio";
import { removeFromMinio } from "../../helper/upload/removeFromMinio";
@ -20,29 +20,34 @@ export const uploadPhoto = async (file: File, project_id: string, userId: string
if (!file || !(file instanceof File) || !file.name) {
return { status: 400, message: "Invalid or missing file", token };
}
const findProject = await db.select().from(projects).where(eq(projects.id, project_id));
// Extract file extension (e.g., ".jpg", ".png")
const fileExtension = file.name.substring(file.name.lastIndexOf("."));
if (findProject.length > 0) {
// Extract file extension (e.g., ".jpg", ".png")
const fileExtension = file.name.substring(file.name.lastIndexOf("."));
// Generate a unique filename using the timestamp
const timestamp = Date.now(); // Current timestamp in milliseconds
const uniqueFileName = `${file.name.split(".")[0]}-${timestamp}${fileExtension}`;
// Generate a unique filename using the timestamp
const timestamp = Date.now(); // Current timestamp in milliseconds
const uniqueFileName = `${file.name.split(".")[0]}-${timestamp}${fileExtension}`;
// Upload file to MinIO with the unique filename
const urlLink = await uploadToMinio(file, project_id, uniqueFileName);
if (!urlLink || !urlLink.url) {
return { status: 500, message: "File upload failed", token };
// Upload file to MinIO with the unique filename
const urlLink = await uploadToMinio(file, project_id, uniqueFileName);
if (!urlLink || !urlLink.url) {
return { status: 500, message: "File upload failed", token };
}
// Save file info in DB with modified filename
const saveFile = await db.insert(uploads).values({
filename: uniqueFileName,
url: urlLink.url,
projectId: project_id,
}).returning();
return { status: 200, message: "File uploaded successfully", data: saveFile, token };
}
else {
return { status: 404, message: "No projects found with this project id", token }
}
// Save file info in DB with modified filename
const saveFile = await db.insert(uploads).values({
filename: uniqueFileName,
url: urlLink.url,
projectId: project_id,
}).returning();
return { status: 200, message: "File uploaded successfully", data: saveFile, token };
} catch (error: any) {
console.error("Error processing file:", error);
return { status: 500, message: "An error occurred while uploading the photo", token };
@ -52,7 +57,7 @@ export const uploadPhoto = async (file: File, project_id: string, userId: string
export const deletePhoto = async (url: string, token: string) => {
try {
if (!url) {
return { status: 404, message: "File ID is missing", token }
return { status: 404, message: "File url is missing", token }
}
const deleteFile = await db