fix: revise route for Assessments
This commit is contained in:
parent
4b7a629517
commit
ab37456906
|
|
@ -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(
|
||||||
|
|
@ -280,12 +252,20 @@ const assessmentsRoute = new Hono<HonoEnv>()
|
||||||
.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);
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -297,13 +277,17 @@ 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
|
||||||
|
|
@ -313,6 +297,8 @@ const assessmentsRoute = new Hono<HonoEnv>()
|
||||||
// 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
|
||||||
|
|
@ -331,18 +317,32 @@ const assessmentsRoute = new Hono<HonoEnv>()
|
||||||
|
|
||||||
// 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) {
|
||||||
|
throw notFound({
|
||||||
|
message: "answerId is required",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
await updateFilenameInDatabase(answerId, path.basename(filePath));
|
await updateFilenameInDatabase(answerId, path.basename(filePath));
|
||||||
}
|
|
||||||
|
|
||||||
// Return the file URL
|
// Set the file URL for the final response
|
||||||
const fileUrl = `/images/${path.basename(filePath)}`;
|
fileUrl = `/images/${path.basename(filePath)}`;
|
||||||
return c.json({ success: true, imageUrl: fileUrl });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.json({ success: false, message: 'No file uploaded' });
|
if (!fileUrl) {
|
||||||
|
throw notFound({
|
||||||
|
message: 'No file uploaded',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
success: true,
|
||||||
|
imageUrl: fileUrl
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -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",
|
||||||
},
|
};
|
||||||
404
|
statusCode = 404;
|
||||||
);
|
} else {
|
||||||
|
response = {
|
||||||
|
message: "Answer updated successfully",
|
||||||
|
answer: updatedAnswer[0],
|
||||||
|
};
|
||||||
|
statusCode = 200;
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.json(
|
return c.json(
|
||||||
|
response,
|
||||||
{
|
{
|
||||||
message: "Answer updated successfully",
|
status: statusCode
|
||||||
answer: updatedAnswer[0],
|
}
|
||||||
},
|
|
||||||
200
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
export default assessmentsRoute;
|
export default assessmentsRoute;
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user