From a3883b7280feb2bc845e5dae83c0ffaba1f1e7f4 Mon Sep 17 00:00:00 2001 From: falendikategar Date: Fri, 18 Oct 2024 14:46:20 +0700 Subject: [PATCH] update: revision for endpoint post upload file in assessments --- apps/backend/src/routes/assessments/route.ts | 86 +++++++++++--------- 1 file changed, 46 insertions(+), 40 deletions(-) diff --git a/apps/backend/src/routes/assessments/route.ts b/apps/backend/src/routes/assessments/route.ts index 646326c..ce1f6c0 100644 --- a/apps/backend/src/routes/assessments/route.ts +++ b/apps/backend/src/routes/assessments/route.ts @@ -42,16 +42,39 @@ export const validationFormSchema = z.object({ export const answerUpdateSchema = answerFormSchema.partial(); -// Helper function to save the file +// Helper untuk menyimpan file async function saveFile(filePath: string, fileBuffer: Buffer): Promise { await fs.promises.writeFile(filePath, fileBuffer); } -// Function to update the filename in the database -async function updateFilenameInDatabase(answerId: string, filename: string): Promise { +// Cari answer berdasarkan assessmentId dan questionId +async function findAnswerId(assessmentId: string, questionId: string): Promise { + const result = await db + .select({ answerId: answers.id }) + .from(answers) + .leftJoin(options, eq(answers.optionId, options.id)) + .where( + and( + eq(answers.assessmentId, assessmentId), + eq(options.questionId, questionId) + ) + ) + .limit(1); - await db.update(answers) - .set({ filename }) + return result.length > 0 ? result[0].answerId : null; +} + +// Update filename di tabel answers +async function updateFilename(answerId: string, filename: string): Promise { + // Dapatkan tanggal dan waktu saat ini + const currentDate = new Date(); + + await db + .update(answers) + .set({ + filename, + updatedAt: currentDate, + }) .where(eq(answers.id, answerId)); } @@ -481,75 +504,58 @@ const assessmentsRoute = new Hono() "/uploadFile", checkPermission("assessments.uploadFile"), async (c) => { - // Get the Content-Type header const contentType = c.req.header('content-type'); if (!contentType || !contentType.includes('multipart/form-data')) { - throw notFound({ - message: "Invalid Content-Type", - }); + return c.json({ message: "Invalid Content-Type" }, 400); } - // Extract boundary const boundary = contentType.split('boundary=')[1]; if (!boundary) { - throw notFound({ - message: "Boundary not found", - }); + return c.json({ message: "Boundary not found" }, 400); } - // Get the raw body const body = await c.req.arrayBuffer(); const bodyString = Buffer.from(body).toString(); - - // Split the body by the boundary const parts = bodyString.split(`--${boundary}`); - let fileUrl = null; + let fileUrl: string | null = null; for (const part of parts) { if (part.includes('Content-Disposition: form-data;')) { - // Extract file name const match = /filename="(.+?)"/.exec(part); if (match) { const fileName = match[1]; const fileContentStart = part.indexOf('\r\n\r\n') + 4; const fileContentEnd = part.lastIndexOf('\r\n'); - - // Extract file content as Buffer const fileBuffer = Buffer.from(part.slice(fileContentStart, fileContentEnd), 'binary'); - // Define file path and save the file - const filePath = path.join('images', Date.now() + '-' + fileName); + const filePath = path.join('files', `${Date.now()}-${fileName}`); await saveFile(filePath, fileBuffer); - // Assuming answerId is passed as a query parameter or in the form-data - const answerId = c.req.query('answerId'); - if (!answerId) { - throw notFound({ - message: "answerId is required", - }); + const assessmentId = c.req.query('assessmentId'); + const questionId = c.req.query('questionId'); + + if (!assessmentId || !questionId) { + return c.json({ message: "assessmentId and questionId are required" }, 400); } - await updateFilenameInDatabase(answerId, path.basename(filePath)); + const answerId = await findAnswerId(assessmentId, questionId); - // Set the file URL for the final response - fileUrl = `/images/${path.basename(filePath)}`; + if (!answerId) { + return c.json({ message: 'Answer not found' }, 404); + } + + await updateFilename(answerId, path.basename(filePath)); + fileUrl = `/files/${path.basename(filePath)}`; } } } if (!fileUrl) { - throw notFound({ - message: 'No file uploaded', - }); + return c.json({ message: 'No file uploaded' }, 400); } - return c.json( - { - success: true, - imageUrl: fileUrl - } - ); + return c.json({ success: true, imageUrl: fileUrl }); } )