Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

052 Dec 5: Iterating the Assessment Tracker and Compliance Tracker #330

Conversation

HarshP4585
Copy link
Contributor

@HarshP4585 HarshP4585 commented Dec 9, 2024

  • Added code to iterate over assessment tracker metadata on POST /assessments endpoint
  • Added code to iterate over compliance tracker metadata on POST /controls endpoint

Affected issues

Summary by CodeRabbit

  • New Features

    • Enhanced assessment creation to support file uploads and a more complex data structure.
    • Added middleware for file uploads in the assessment creation route.
  • Bug Fixes

    • Removed unnecessary file upload handling from the question creation route.
  • Refactor

    • Updated method signatures and request handling for assessments to accommodate new requirements.

@HarshP4585 HarshP4585 added the backend Backend related tasks/issues label Dec 9, 2024
@HarshP4585 HarshP4585 self-assigned this Dec 9, 2024
Copy link

coderabbitai bot commented Dec 9, 2024

Walkthrough

The pull request introduces significant modifications to the assessment creation functionality within the application. The createAssessment function in assessment.ctrl.ts is updated to handle a more complex data structure, including file uploads. The associated route in assessment.route.ts is modified to utilize multer for file handling, while the question.route.ts removes file upload handling. These changes enhance the ability to create assessments with nested topics and questions while managing file uploads effectively.

Changes

File Path Change Summary
Servers/controllers/assessment.ctrl.ts Updated createAssessment to use RequestWithFile, expanded newAssessment structure, added logic for nested topics and questions, and modified response handling.
Servers/routes/assessment.route.ts Added multer middleware for file uploads in the POST route for assessments.
Servers/routes/question.route.ts Removed multer handling and adjusted POST route to call createQuestion directly.

Possibly related PRs

  • 051 Nov 29 Storing Evidence files #308: This PR modifies the question.ctrl.ts file to introduce file upload handling in the createQuestion and updateQuestionById functions, which is directly related to the changes made in the main PR that also enhances the createAssessment function for file uploads.
  • file upload component with Uppy #306: This PR introduces a file upload component using Uppy, which aligns with the main PR's focus on handling file uploads in the assessment creation process.
  • 050 Nov 29: Use DB for the API calls instead of mock data #304: Although this PR primarily focuses on changing how mock data is handled, it also affects the createAssessment function, which is relevant to the changes made in the main PR.

Suggested labels

enhancement

Suggested reviewers

  • MuhammadKhalilzadeh
  • gorkem-bwl

Poem

Hop, hop, hooray, in code we play,
Assessments now can have files on display.
With topics and questions, oh what a sight,
Our data structures grow, reaching new height!
So let’s celebrate this change with glee,
For every new feature, brings joy to me! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (2)
Servers/controllers/assessment.ctrl.ts (2)

86-102: Consider defining an interface for newAssessment for better readability

The in-line type definition for newAssessment is quite complex. Defining an interface or type alias would improve readability and maintainability.

You can define an interface outside the function:

interface NewAssessment {
  projectId: number;
  title: string;
  subTopics: {
    id: number;
    title: string;
    questions: {
      id: number;
      question: string;
      hint: string;
      priorityLevel: string;
      answerType: string;
      inputType: string;
      isRequired: boolean;
      evidenceFileRequired: boolean;
      evidenceFile: string;
    }[];
  }[];
}

Then update the variable declaration:

-const newAssessment: { ... }[] = req.body;
+const newAssessment: NewAssessment[] = req.body;

113-161: Consider refactoring to eliminate the use of labels for better code clarity

Using the mainLoop label and break mainLoop to control flow through nested asynchronous loops can reduce code readability. Labels are generally discouraged. Consider refactoring to avoid labels, possibly by using functions or additional condition checks.

One possible approach is to refactor the nested loops into separate async functions and use return statements to exit early on failure. For example:

async function processAssessment(topicGroup: NewAssessment): Promise<boolean> {
  if (!topicGroup.projectId) {
    return false;
  }
  // ... rest of the code
  return true;
}

// In your main function
let flag = true;
for (const topicGroup of newAssessment) {
  flag = await processAssessment(topicGroup);
  if (!flag) {
    break;
  }
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 117-117: Unnecessary label.

Safe fix: Remove the unnecessary label.
You can achieve the same result without the label.

(lint/complexity/noUselessLabel)


[error] 129-129: Unnecessary label.

Safe fix: Remove the unnecessary label.
You can achieve the same result without the label.

(lint/complexity/noUselessLabel)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 74cdf76 and d054d9a.

📒 Files selected for processing (3)
  • Servers/controllers/assessment.ctrl.ts (3 hunks)
  • Servers/routes/assessment.route.ts (2 hunks)
  • Servers/routes/question.route.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
Servers/controllers/assessment.ctrl.ts

[error] 117-117: Unnecessary label.

Safe fix: Remove the unnecessary label.
You can achieve the same result without the label.

(lint/complexity/noUselessLabel)


[error] 129-129: Unnecessary label.

Safe fix: Remove the unnecessary label.
You can achieve the same result without the label.

(lint/complexity/noUselessLabel)

🔇 Additional comments (3)
Servers/controllers/assessment.ctrl.ts (2)

19-21: Imports are appropriate and correctly added

The necessary imports for createNewQuestionQuery, createNewTopicQuery, createNewSubtopicQuery, and RequestWithFile have been correctly added.


80-80: Update of request type to RequestWithFile is appropriate

Changing the request type to RequestWithFile accommodates file uploads in the createAssessment function.

Servers/routes/question.route.ts (1)

19-19: Removal of file upload middleware aligns with updated file handling

Since file uploads are now managed in the assessment route, removing the upload.any("files") middleware from the question route is appropriate.

Comment on lines +163 to +167
if (flag) {
return res.status(201).json(STATUS_CODE[201]({}));
}

return res.status(503).json(STATUS_CODE[503]({}));
return res.status(204).json(STATUS_CODE[204]({}));
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Return an appropriate error status code instead of 204 when creation fails

Returning a 204 No Content status when the assessment creation fails may be misleading. A 400 (Bad Request) or 500 (Internal Server Error) status code would better indicate that the operation did not succeed.

Apply this diff to return a more suitable error status code:

-if (flag) {
-  return res.status(201).json(STATUS_CODE[201]({}));
-}
-
-return res.status(204).json(STATUS_CODE[204]({}));
+if (flag) {
+  return res.status(201).json(STATUS_CODE[201]({}));
+} else {
+  return res.status(400).json(STATUS_CODE[400]({ message: "Assessment creation failed" }));
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (flag) {
return res.status(201).json(STATUS_CODE[201]({}));
}
return res.status(503).json(STATUS_CODE[503]({}));
return res.status(204).json(STATUS_CODE[204]({}));
if (flag) {
return res.status(201).json(STATUS_CODE[201]({}));
} else {
return res.status(400).json(STATUS_CODE[400]({ message: "Assessment creation failed" }));
}

@@ -16,7 +18,7 @@ router.get("/", /*authenticateJWT, */ getAllAssessments);
router.get("/:id", /*authenticateJWT, */ getAssessmentById);

// POST, PUT, DELETE requests
router.post("/", /*authenticateJWT, */ createAssessment);
router.post("/", /*authenticateJWT, */ upload.any("files"), createAssessment);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Adjust multer middleware usage: upload.any() does not accept field names

The upload.any() method from multer does not accept any arguments. It accepts files from any field name. If you intend to accept files from a specific field, consider using upload.array('files') or upload.single('file') as appropriate.

Apply this diff to use the correct multer middleware method:

-router.post("/", /*authenticateJWT, */ upload.any("files"), createAssessment);
+router.post("/", /*authenticateJWT, */ upload.array("files"), createAssessment);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
router.post("/", /*authenticateJWT, */ upload.any("files"), createAssessment);
router.post("/", /*authenticateJWT, */ upload.array("files"), createAssessment);

@@ -1,5 +1,7 @@
import express from "express";
const router = express.Router();
const multer = require("multer");
const upload = multer({ Storage: multer.memoryStorage() });
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix the option name 'Storage' to 'storage' in multer configuration

The configuration option for multer should be storage (lowercase 's'), not Storage. Using the incorrect option name will prevent multer from working properly.

Apply this diff to fix the typo:

-const upload = multer({ Storage: multer.memoryStorage() });
+const upload = multer({ storage: multer.memoryStorage() });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const upload = multer({ Storage: multer.memoryStorage() });
const upload = multer({ storage: multer.memoryStorage() });

Copy link
Collaborator

@MuhammadKhalilzadeh MuhammadKhalilzadeh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you very much @HarshP4585 for the nice code 🙏🏻, like always 🍻

However, there are a couple of things.
We both have done almost the same thing here, but the differences in our codes are:

1- You've only done the development in the server-side, but I have completed its implementation on both Client and Server side.
2 There were some fields that were missing, like the answer to questions itself 🤣
So, now I've added them.

  1. Now, You sir, have implemented the file uploaded related parts.

So, here's what we're going to do:

I'll merge my pr.
the you please, implemented the details that you have and I haven't.

Also please make sure everything in this potion works fine.

Regards,
Mo

@HarshP4585 HarshP4585 closed this Dec 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backend Backend related tasks/issues
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants