fix: revise route for Assessments

This commit is contained in:
falendikategar 2024-08-20 12:24:28 +07:00
parent 4b7a629517
commit ab37456906

View File

@ -13,6 +13,7 @@ import authInfo from "../../middlewares/authInfo";
import checkPermission from "../../middlewares/checkPermission"; import checkPermission from "../../middlewares/checkPermission";
import path from "path"; import path from "path";
import fs from 'fs'; import fs from 'fs';
import { notFound } from "../../errors/DashboardError";
export const answerFormSchema = z.object({ export const answerFormSchema = z.object({
optionId: z.string().min(1), optionId: z.string().min(1),
@ -30,12 +31,10 @@ async function saveFile(filePath: string, fileBuffer: Buffer): Promise<void> {
} }
// Function to update the filename in the database // Function to update the filename in the database
async function updateFilenameInDatabase(answerId: string, flname: string): Promise<void> { async function updateFilenameInDatabase(answerId: string, filename: string): Promise<void> {
await db.update(answers) await db.update(answers)
.set({ .set({ filename })
filename: flname,
})
.where(eq(answers.id, answerId)); .where(eq(answers.id, answerId));
} }
@ -76,23 +75,14 @@ const assessmentsRoute = new Hono<HonoEnv>()
.get( .get(
"/getAllQuestions", "/getAllQuestions",
checkPermission("assessments.readAllQuestions"), checkPermission("assessments.readAllQuestions"),
requestValidator(
"query",
z.object({
page: z.coerce.number().int().min(0).default(0),
limit: z.coerce.number().int().min(1).max(1000).default(1000),
q: z.string().default(""),
})
),
async (c) => { async (c) => {
const { page, limit, q } = c.req.valid("query");
const totalCountQuery = const totalCountQuery =
sql<number>`(SELECT count(*) sql<number>`(SELECT count(*)
FROM ${options} FROM ${options}
LEFT JOIN ${questions} ON ${options.questionId} = ${questions.id} LEFT JOIN ${questions} ON ${options.questionId} = ${questions.id}
LEFT JOIN ${subAspects} ON ${questions.subAspectId} = ${subAspects.id} LEFT JOIN ${subAspects} ON ${questions.subAspectId} = ${subAspects.id}
LEFT JOIN ${aspects} ON ${subAspects.aspectId} = ${aspects.id} LEFT JOIN ${aspects} ON ${subAspects.aspectId} = ${aspects.id}
WHERE ${questions.deletedAt} IS NULL
)`; )`;
const result = await db const result = await db
@ -112,34 +102,15 @@ const assessmentsRoute = new Hono<HonoEnv>()
.leftJoin(questions, eq(options.questionId, questions.id)) .leftJoin(questions, eq(options.questionId, questions.id))
.leftJoin(subAspects, eq(questions.subAspectId, subAspects.id)) .leftJoin(subAspects, eq(questions.subAspectId, subAspects.id))
.leftJoin(aspects, eq(subAspects.aspectId, aspects.id)) .leftJoin(aspects, eq(subAspects.aspectId, aspects.id))
.where( .where(sql`${questions.deletedAt} IS NULL`)
and(
q
? or(
ilike(aspects.name, q),
ilike(subAspects.name, q),
ilike(questions.question, q),
ilike(options.text, q),
ilike(options.score, q),
eq(options.id, q),
)
: undefined
)
)
.offset(page * limit)
.limit(limit);
return c.json({ return c.json({
data: result.map((d) => ({ ...d, fullCount: undefined })), data: result.map((d) => (
_metadata: { {
currentPage: page, ...d,
totalPages: Math.ceil( fullCount: undefined
(Number(result[0]?.fullCount) ?? 0) / limit }
), )),
totalItems: Number(result[0]?.fullCount) ?? 0,
perPage: limit,
},
}); });
} }
) )
@ -165,7 +136,10 @@ const assessmentsRoute = new Hono<HonoEnv>()
const { assessmentId, page, limit, q } = c.req.valid("query"); const { assessmentId, page, limit, q } = c.req.valid("query");
// Query to count total answers for the specific assessmentId // Query to count total answers for the specific assessmentId
const totalCountQuery = sql<number>`(SELECT count(*) FROM ${answers} WHERE ${answers.assessmentId} = ${assessmentId})`; const totalCountQuery =
sql<number>`(SELECT count(*)
FROM ${answers}
WHERE ${answers.assessmentId} = ${assessmentId})`;
// Query to retrieve answers for the specific assessmentId // Query to retrieve answers for the specific assessmentId
const result = await db const result = await db
@ -225,12 +199,11 @@ const assessmentsRoute = new Hono<HonoEnv>()
.limit(1); .limit(1);
if (!currentAnswer.length) { if (!currentAnswer.length) {
return c.json( throw notFound(
{ {
message: "Answer not found", message: "Answer not found",
}, }
404 )
);
} }
// Toggle the isFlagged value // Toggle the isFlagged value
@ -246,12 +219,11 @@ const assessmentsRoute = new Hono<HonoEnv>()
.returning(); .returning();
if (!updatedAnswer.length) { if (!updatedAnswer.length) {
return c.json( throw notFound(
{ {
message: "Failed to update answer", message: "Failed to update answer",
}, }
500 )
);
} }
return c.json( return c.json(
@ -270,7 +242,7 @@ const assessmentsRoute = new Hono<HonoEnv>()
checkPermission("assessments.checkAnswer"), checkPermission("assessments.checkAnswer"),
async (c) => { async (c) => {
const { optionId, assessmentId } = await c.req.json(); const { optionId, assessmentId } = await c.req.json();
const result = await db const result = await db
.select() .select()
.from(answers) .from(answers)
@ -278,16 +250,24 @@ const assessmentsRoute = new Hono<HonoEnv>()
and(eq(answers.optionId, optionId), eq(answers.assessmentId, assessmentId)) and(eq(answers.optionId, optionId), eq(answers.assessmentId, assessmentId))
) )
.execute(); .execute();
const existingAnswer = result[0]; const existingAnswer = result[0];
let response;
if (existingAnswer) { if (existingAnswer) {
return c.json({ exists: true, answerId: existingAnswer.id }); response = {
exists: true,
answerId: existingAnswer.id
};
} else { } else {
return c.json({ exists: false }); response = {
exists: false
};
} }
return c.json(response);
} }
) )
// Upload filename to the table answers and save the file on the local storage // Upload filename to the table answers and save the file on the local storage
.post( .post(
@ -297,22 +277,28 @@ const assessmentsRoute = new Hono<HonoEnv>()
// Get the Content-Type header // Get the Content-Type header
const contentType = c.req.header('content-type'); const contentType = c.req.header('content-type');
if (!contentType || !contentType.includes('multipart/form-data')) { if (!contentType || !contentType.includes('multipart/form-data')) {
return c.json({ success: false, message: 'Invalid Content-Type' }); throw notFound({
message: "Invalid Content-Type",
});
} }
// Extract boundary // Extract boundary
const boundary = contentType.split('boundary=')[1]; const boundary = contentType.split('boundary=')[1];
if (!boundary) { if (!boundary) {
return c.json({ success: false, message: 'Boundary not found' }); throw notFound({
message: "Boundary not found",
});
} }
// Get the raw body // Get the raw body
const body = await c.req.arrayBuffer(); const body = await c.req.arrayBuffer();
const bodyString = Buffer.from(body).toString(); const bodyString = Buffer.from(body).toString();
// Split the body by the boundary // Split the body by the boundary
const parts = bodyString.split(`--${boundary}`); const parts = bodyString.split(`--${boundary}`);
let fileUrl = null;
for (const part of parts) { for (const part of parts) {
if (part.includes('Content-Disposition: form-data;')) { if (part.includes('Content-Disposition: form-data;')) {
// Extract file name // Extract file name
@ -321,30 +307,44 @@ const assessmentsRoute = new Hono<HonoEnv>()
const fileName = match[1]; const fileName = match[1];
const fileContentStart = part.indexOf('\r\n\r\n') + 4; const fileContentStart = part.indexOf('\r\n\r\n') + 4;
const fileContentEnd = part.lastIndexOf('\r\n'); const fileContentEnd = part.lastIndexOf('\r\n');
// Extract file content as Buffer // Extract file content as Buffer
const fileBuffer = Buffer.from(part.slice(fileContentStart, fileContentEnd), 'binary'); const fileBuffer = Buffer.from(part.slice(fileContentStart, fileContentEnd), 'binary');
// Define file path and save the file // Define file path and save the file
const filePath = path.join('images', Date.now() + '-' + fileName); const filePath = path.join('images', Date.now() + '-' + fileName);
await saveFile(filePath, fileBuffer); await saveFile(filePath, fileBuffer);
// Assuming answerId is passed as a query parameter or in the form-data // Assuming answerId is passed as a query parameter or in the form-data
const answerId = c.req.query('answerId'); const answerId = c.req.query('answerId');
if (answerId) { if (!answerId) {
await updateFilenameInDatabase(answerId, path.basename(filePath)); throw notFound({
message: "answerId is required",
});
} }
// Return the file URL await updateFilenameInDatabase(answerId, path.basename(filePath));
const fileUrl = `/images/${path.basename(filePath)}`;
return c.json({ success: true, imageUrl: fileUrl }); // Set the file URL for the final response
fileUrl = `/images/${path.basename(filePath)}`;
} }
} }
} }
return c.json({ success: false, message: 'No file uploaded' }); if (!fileUrl) {
throw notFound({
message: 'No file uploaded',
});
}
return c.json(
{
success: true,
imageUrl: fileUrl
}
);
} }
) )
// Submit option to table answers from use-form in frontend // Submit option to table answers from use-form in frontend
.post( .post(
@ -384,6 +384,8 @@ const assessmentsRoute = new Hono<HonoEnv>()
const answerId = c.req.param("id"); const answerId = c.req.param("id");
const answerData = c.req.valid("json"); const answerData = c.req.valid("json");
let response;
let statusCode;
const updatedAnswer = await db const updatedAnswer = await db
.update(answers) .update(answers)
.set({ .set({
@ -393,23 +395,25 @@ const assessmentsRoute = new Hono<HonoEnv>()
.returning(); .returning();
if (!updatedAnswer.length) { if (!updatedAnswer.length) {
return c.json( response = {
{ message: "Answer not found or update failed",
message: "Answer not found or update failed", };
}, statusCode = 404;
404 } else {
); response = {
message: "Answer updated successfully",
answer: updatedAnswer[0],
};
statusCode = 200;
} }
return c.json( return c.json(
{ response,
message: "Answer updated successfully", {
answer: updatedAnswer[0], status: statusCode
}, }
200
); );
} }
) )
export default assessmentsRoute; export default assessmentsRoute;