upload routes tested

This commit is contained in:
Saimon8420 2025-02-01 17:43:17 +06:00
parent 73631d1972
commit 15d1f6967e
6 changed files with 28 additions and 23 deletions

View file

@ -55,7 +55,7 @@ export const createProject = async (userId: string) => {
try {
const { id } = await createEmptyProject(userId);
const bucket = await createBucket(id);
return { status: 200, message: "New project created and file uploaded successfully", data: { id, bucketName: bucket } };
return { status: 200, message: "New project created successfully", data: { id, bucketName: bucket } };
} catch (error: any) {
console.log(error.message);
@ -91,7 +91,6 @@ export const updateProject = async (id: string, body: any) => {
}
};
export const deleteProject = async (id: string) => {
try {
const deleteProject = await db.delete(projects).where(eq(projects.id, id)).returning({ id: projects.id });

View file

@ -4,19 +4,15 @@ import { uploads } from "../../db/schema";
import { uploadToMinio } from "../../helper/upload/uploadToMinio";
import { removeFromMinio } from "../../helper/upload/removeFromMinio";
export const uploadPhoto = async (formData: FormData, userId: string) => {
export const uploadPhoto = async (file: File, project_id: string, userId: string) => {
try {
// Validate userId
if (!userId || typeof userId !== "string") {
return { status: 400, message: "Invalid user ID" };
}
// Extract form data
const projectId = formData.get("id");
const file = formData.get("file");
// Validate projectId
if (!projectId || typeof projectId !== "string") {
if (!project_id || typeof project_id !== "string") {
return { status: 400, message: "Invalid project ID" };
}
@ -25,17 +21,24 @@ export const uploadPhoto = async (formData: FormData, userId: string) => {
return { status: 400, message: "Invalid or missing file" };
}
// Upload file
const urlLink = await uploadToMinio(file, projectId, file.name);
// 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}`;
// 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" };
}
// Save file info in DB
// Save file info in DB with modified filename
const saveFile = await db.insert(uploads).values({
filename: file.name,
filename: uniqueFileName,
url: urlLink.url,
projectId
projectId: project_id,
}).returning();
return { status: 200, message: "File uploaded successfully", data: saveFile };

View file

@ -16,10 +16,10 @@ export const uploadRoutes = new Elysia({
return { userId: authData.userId }; // Inject into context
});
uploadRoutes.post("/add", async ({ request, userId }) => {
uploadRoutes.post("/add", async ({ body, userId }) => {
const user_id: String | any = userId;
const formData = await request.formData();
return uploadPhoto(formData, user_id);
const { id: project_id, file } = body;
return uploadPhoto(file, project_id, user_id);
}, {
body: t.Object({
file: t.File(),
@ -27,9 +27,12 @@ uploadRoutes.post("/add", async ({ request, userId }) => {
})
});
uploadRoutes.delete("/delete/:uploads_url", async ({ params: { uploads_url } }) => deletePhoto(uploads_url), {
params: t.Object({
uploads_url: t.String(),
uploadRoutes.delete("/delete", async ({ query }) => {
const { url } = query;
return deletePhoto(url);
}, {
query: t.Object({
url: t.String(),
})
});

View file

@ -14,6 +14,8 @@ const allowedOrigins = [
const app = new Elysia()
.use(cors({
origin: allowedOrigins,
methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With", "Accept", "Origin", "Access-Control-Allow-Origin"],
credentials: true,
}))
.use(swagger({

View file

@ -26,9 +26,8 @@ export const createBucket = async (bucketName: string) => {
} else {
return bucketName; // Return the bucket name if it already exists
}
} catch (error) {
} catch (error: any) {
console.error("Error creating or configuring bucket:", error);
// Optionally rethrow the error with additional context
throw new Error(`Error creating bucket "${bucketName}": ${error.message}`);
}

View file

@ -11,9 +11,8 @@ export const uploadToMinio = async (file: File, bucketName: string, objectName:
return { url: publicUrl };
} catch (error) {
} catch (error: any) {
console.error("Error uploading file to MinIO:", error);
throw new Error(`Error uploading file: ${error.message}`);
}
};