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

Refactor Popup Validations #549

Merged
merged 14 commits into from
Feb 24, 2025

Conversation

Anurag9977
Copy link

Refactored Popup Validations in Backend

Updated the existing popup validations in popup.controller.js file using express validator and placed them in popup.helper.js file.

This PR addresses the issue #387

Below is a summary of all the changes:

  • Added
  1. Validation rules : addOrUpdatePopupValidation, deleteOrGetPopupByIdValidation, getPopupByUrlValidation added in popup.helper.js file.
  2. Above mentioned validations also added as middlewares in the below routes in the popup.routes.js file.
    add_popup, delete_popup/:id, edit_popup/:id, get_popup/:id, get_popup_by_url
  • Removed
  1. Existing validation code removed from popup.controller.js file.

Existing functions in popup.helper.js file such as validatePopupSize, validatePopupSizeWrapper, validateRelativeUrl, validateUrl have been left as is since they might be useful in another implementations.

Copy link
Contributor

coderabbitai bot commented Feb 19, 2025

Walkthrough

This pull request updates documentation and refactors backend validations for popup functionalities. The README now includes a demo link, clarified installation instructions, optional steps for symbolic link creation and Certbot, a JavaScript snippet version update, and updated project names. In the backend, inline validations and error handling have been removed from popup controller methods, replaced by validation middleware in the routes. Centralized validation rules are introduced in a helper module using the express-validator library.

Changes

Files Change Summary
README.md Updated documentation with a new demo link, clarified installation instructions, marked certain steps as optional, updated JavaScript snippet (from agent-1.0.0 to agent-1.0.2), and replaced old project names.
backend/src/controllers/popup.controller.js, backend/src/routes/popup.routes.js, backend/src/utils/popup.helper.js Removed inline validations and associated error handling from popup controllers; added appropriate validation middleware to routes; and introduced centralized express-validator rules (with hexColorPattern) in the helper module.
backend/src/test/e2e/popup.test.mjs, backend/src/test/unit/controllers/popup.test.js Simplified error messages in test cases for popups, changing structure from objects to direct strings for clearer feedback on validation issues.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant R as Route Handler
    participant V as Validation Middleware
    participant P as Popup Controller

    C->>R: Send HTTP Request (e.g., POST /add_popup)
    R->>V: Apply addOrUpdatePopupValidation & handleValidationErrors
    V-->>R: Return validation result
    R->>P: Forward request to addPopup
    P-->>R: Process and return response
    R-->>C: Deliver final response
Loading

Possibly related PRs

  • removed "Creator" from all the returned responses #447: The changes in the main PR, which involve modifications to the PopupController and related validation logic, are directly related to the changes in the retrieved PR, as both involve the Popup functionality and the removal of the creator field from responses in the popup service.
  • Banner validation (Backend) #497: The changes in the main PR focus on removing validation checks and error handling in the PopupController methods, while the retrieved PR similarly removes validation checks in the BannerController methods, indicating a related approach to simplifying validation logic in both controllers.
  • Refactor Popup Validations #548: The changes in the main PR and the retrieved PR are directly related as both involve significant modifications to the validation logic in the PopupController class and the introduction of new validation middleware in the routes, specifically affecting the same methods and validation processes.

Suggested reviewers

  • swoopertr

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between da4babc and 51c719c.

📒 Files selected for processing (2)
  • backend/src/test/e2e/popup.test.mjs (18 hunks)
  • backend/src/test/unit/controllers/popup.test.js (0 hunks)
💤 Files with no reviewable changes (1)
  • backend/src/test/unit/controllers/popup.test.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/test/e2e/popup.test.mjs

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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. (Beta)
  • @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.

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
Contributor

@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: 1

🧹 Nitpick comments (4)
backend/src/routes/popup.routes.js (1)

15-16: Yo dawg, we need some validation here too!

Consider adding validation middleware to all_popups and popups routes for consistency.

-router.get("/all_popups", authenticateJWT, popupController.getAllPopups);
-router.get("/popups", authenticateJWT, popupController.getPopups);
+router.get("/all_popups", authenticateJWT, handleValidationErrors, popupController.getAllPopups);
+router.get("/popups", authenticateJWT, handleValidationErrors, popupController.getPopups);
backend/src/utils/popup.helper.js (1)

47-66: These color validations be looking clean! But let's make them clearer! 🎨

Consider providing more specific error messages that include the allowed formats.

   body('headerBackgroundColor')
     .optional()
     .matches(hexColorPattern)
-    .withMessage('Header background color must be a valid hex color code'),
+    .withMessage('Header background color must be a valid hex color code (e.g., #FFF, #FFFF, #FFFFFF, or #FFFFFFFF)'),
README.md (2)

242-252: Yo, let's fix that code block formatting! 📝

Add a language identifier to the fenced code block for better syntax highlighting.

-```
+```javascript
 window.bwApiBaseUrl = 'https://guidefox-demo.bluewavelabs.ca/api/';
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

242-242: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)


275-275: Grammar check, fam! 📚

Fix the article usage before "secure".

-DataHall, an secure file sharing application, aka dataroom.
+DataHall, a secure file sharing application, aka dataroom.
🧰 Tools
🪛 LanguageTool

[misspelling] ~275-~275: Use “a” instead of ‘an’ if the following word doesn’t start with a vowel sound, e.g. ‘a sentence’, ‘a university’.
Context: ...s://github.com/bluewave-labs/datahall), an secure file sharing application, aka da...

(EN_A_VS_AN)

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 18c9d81 and 6d7ba1a.

📒 Files selected for processing (4)
  • README.md (5 hunks)
  • backend/src/controllers/popup.controller.js (0 hunks)
  • backend/src/routes/popup.routes.js (1 hunks)
  • backend/src/utils/popup.helper.js (2 hunks)
💤 Files with no reviewable changes (1)
  • backend/src/controllers/popup.controller.js
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

242-242: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

🪛 LanguageTool
README.md

[misspelling] ~275-~275: Use “a” instead of ‘an’ if the following word doesn’t start with a vowel sound, e.g. ‘a sentence’, ‘a university’.
Context: ...s://github.com/bluewave-labs/datahall), an secure file sharing application, aka da...

(EN_A_VS_AN)

🔇 Additional comments (2)
backend/src/routes/popup.routes.js (2)

6-7: Yo, these imports are fire! 🔥

Clean separation of validation middleware and helpers enhances code maintainability.


12-14: These routes are straight fire with that validation! 🎯

Solid implementation of authentication, access control, and validation middleware.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@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: 0

🧹 Nitpick comments (3)
backend/src/utils/popup.helper.js (3)

41-50: Yo, the actionUrl validation needs some cleanup! 🧹

The error handling in actionUrl validation isn't consistent with the url validation above it.

Let's make it match the style:

   body('actionUrl')
     .custom((value) => {
       if(!value) return true;
       try {
         const url = new URL(value);
-        return ['http:', 'https:'].includes(url.protocol)
-      }catch {
-        return false
+        return ['http:', 'https:'].includes(url.protocol);
+      } catch (error) {
+        return false;
       }
     })

73-75: Mom's spaghetti says we need more validation! 🍝

The ID and URL validations could use some additional safeguards.

Consider these enhancements:

-const deleteOrGetPopupByIdValidation = [param('id').notEmpty().trim().isInt().withMessage("Invalid popup id")]
+const deleteOrGetPopupByIdValidation = [
+  param('id')
+    .notEmpty()
+    .trim()
+    .isInt({ min: 1 })
+    .withMessage("Invalid popup id - must be a positive integer")
+]

-const getPopupByUrlValidation = [body('url').notEmpty().isString().withMessage('URL is missing or invalid')]
+const getPopupByUrlValidation = [
+  body('url')
+    .notEmpty()
+    .isString()
+    .trim()
+    .isURL({ protocols: ['http', 'https'] })
+    .withMessage('URL must be a valid HTTP/HTTPS URL')
+]

77-110: These helper functions need some documentation love! 📝

The existing validation functions are solid but could use some JSDoc comments for better maintainability.

Add documentation like this:

+/**
+ * Validates if the given popup size is one of the allowed values
+ * @param {string} value - The popup size to validate
+ * @returns {boolean} - True if size is valid, false otherwise
+ */
 const validatePopupSize = (value) => {
   const validSizes = settings.popup.size;
   return validSizes.includes(value);
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d7ba1a and 989fbe5.

📒 Files selected for processing (1)
  • backend/src/utils/popup.helper.js (2 hunks)
🔇 Additional comments (2)
backend/src/utils/popup.helper.js (2)

1-4: Yo dawg, that hex color regex is straight fire! 🔥

The hex color pattern supports all valid formats (3,4,6,8 digits). Clean imports and solid regex definition.


112-120: Clean exports, we're done here! ✨

All validation functions and arrays are properly exported. Nice organization!

@Anurag9977
Copy link
Author

@erenfn - PR raised and added the suggestion from the code rabbit review.
Let me know if any additional changes are needed.
Thanks.

Copy link
Contributor

@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: 2

🔭 Outside diff range comments (1)
backend/src/utils/popup.helper.js (1)

78-111: 🛠️ Refactor suggestion

Time to drop some legacy code like it's hot! 🔥

These helper functions are now redundant since we've moved to express-validator. Consider deprecating them with a migration plan:

  1. Add deprecation warnings
  2. Update any existing usage to use the new validation rules
  3. Remove in next major version
 const validatePopupSize = (value) => {
+  console.warn('Deprecated: Use express-validator rules instead');
   const validSizes = settings.popup.size;
   return validSizes.includes(value);
 };
🧹 Nitpick comments (3)
backend/src/utils/popup.helper.js (3)

1-4: Yo dawg, let's make those protocols a constant! 🎵

The setup looks clean, but we're seeing those protocols repeated throughout. Let's drop this at the top:

 const { body, param } = require('express-validator');
 const settings = require('../../config/settings');
 const hexColorPattern = /^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/;
+const ALLOWED_PROTOCOLS = ['http:', 'https:'];

74-76: Break it down like a rap verse! 🎤

Let's make these validations more readable by breaking them into multiple lines:

-const deleteOrGetPopupByIdValidation = [param('id').notEmpty().trim().isInt({ min: 1 }).withMessage("Invalid popup id")]
+const deleteOrGetPopupByIdValidation = [
+  param('id')
+    .notEmpty()
+    .trim()
+    .isInt({ min: 1 })
+    .withMessage("Invalid popup id")
+];

-const getPopupByUrlValidation = [body('url').notEmpty().isString().withMessage('URL is missing or invalid')]
+const getPopupByUrlValidation = [
+  body('url')
+    .notEmpty()
+    .isString()
+    .withMessage('URL is missing or invalid')
+];

113-121: Drop some documentation beats! 📝

Let's add some JSDoc swagger to these exports:

+/**
+ * @typedef {import('express-validator').ValidationChain[]} ValidationRules
+ */

 module.exports = {
+  /** @type {ValidationRules} Rules for adding or updating popups */
   addOrUpdatePopupValidation,
+  /** @type {ValidationRules} Rules for validating popup ID in params */
   deleteOrGetPopupByIdValidation,
+  /** @type {ValidationRules} Rules for validating popup URL in body */
   getPopupByUrlValidation,
+  /** @deprecated Use express-validator rules instead */
   validatePopupSize,
+  /** @deprecated Use express-validator rules instead */
   validatePopupSizeWrapper,
+  /** @deprecated Use express-validator rules instead */
   validateUrl,
+  /** @deprecated Use express-validator rules instead */
   validateRelativeUrl,
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 989fbe5 and d489663.

📒 Files selected for processing (1)
  • backend/src/utils/popup.helper.js (2 hunks)

Copy link
Contributor

@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: 1

♻️ Duplicate comments (1)
backend/src/utils/popup.helper.js (1)

71-76: 🛠️ Refactor suggestion

This URL validation's got one shot, one opportunity! 🎯

Let's make it more robust by reusing our URL validation logic:

 const getPopupByUrlValidation = [
   body('url')
     .notEmpty()
-    .isString()
-    .withMessage('URL is missing or invalid')
+    .isString()
+    .withMessage('URL must be a string')
+    .bail()
+    .custom((value) => {
+      if (value.startsWith('/')) {
+        return /^\/[\w-]+(\/[\w-]+)*(\?.*)?$/.test(value);
+      }
+      try {
+        const url = new URL(value);
+        return ['http:', 'https:'].includes(url.protocol);
+      } catch {
+        return false;
+      }
+    })
+    .withMessage('Invalid URL format. Must be a valid relative or absolute URL')
 ]
🧹 Nitpick comments (3)
backend/src/utils/popup.helper.js (3)

3-7: Yo dawg, let's make this color validation more lit! 🎨

The color validation is solid, but we can make it even better:

-const hexColorPattern = /^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/;
+// Supports 3-digit (RGB), 4-digit (RGBA), 6-digit (RRGGBB), and 8-digit (RRGGBBAA) hex colors
+const hexColorPattern = /^#([A-Fa-f0-9]{3,4}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/i;

63-69: These ID validations straight fire, but the message could be more precise! 🎯

     .notEmpty()
     .trim()
     .isInt({ min: 1 })
-    .withMessage("Invalid popup id")
+    .withMessage("Popup ID must be a positive integer")

78-111: These old helpers looking kinda sus! 🤔

Consider adding deprecation notices to these functions since we've moved to express-validator:

+/**
+ * @deprecated Use express-validator middleware instead.
+ * See addOrUpdatePopupValidation for the new implementation.
+ */
 const validatePopupSize = (value) => {
   const validSizes = settings.popup.size;
   return validSizes.includes(value);
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d489663 and 6778058.

📒 Files selected for processing (1)
  • backend/src/utils/popup.helper.js (2 hunks)
🔇 Additional comments (1)
backend/src/utils/popup.helper.js (1)

113-121: Exports looking clean, no spaghetti code here! 🍝

The module exports are well-organized, clearly separating the new validation middleware from the existing helper functions.

@erenfn erenfn self-requested a review February 23, 2025 23:28
Copy link
Collaborator

@erenfn erenfn left a comment

Choose a reason for hiding this comment

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

The endpoints are working good!

There is just one more issue left. At the bottom of the PR you can see that some tests for popups fail. Can you change the tests accordingly? You can follow what @DeboraSerra did at #490

Copy link
Contributor

@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: 0

🔭 Outside diff range comments (2)
backend/src/test/unit/controllers/popup.test.js (2)

418-418: ⚠️ Potential issue

Fix duplicate error message in array.

The error message array contains a duplicate entry for textColor validation.

Apply this diff to fix the duplicate error message:

-        errors: ['textColor must be a valid hex color code']['textColor must be a valid hex color code'],
+        errors: ['textColor must be a valid hex color code'],

180-181: 🛠️ Refactor suggestion

Standardize error message format.

Some error messages still use the old object format with msg property while others use the new string array format. This inconsistency should be fixed.

Apply this diff to standardize the error message format:

-        errors: [{ msg: "Popup with the specified id does not exist" }],
+        errors: ["Popup with the specified id does not exist"],

-        errors: [{ msg: "Popup not found" }],
+        errors: ["Popup not found"],

Also applies to: 453-454, 621-625

🧹 Nitpick comments (2)
backend/src/test/e2e/popup.test.mjs (2)

640-644: Remove commented-out test assertion.

There's a commented-out assertion that should either be implemented or removed.

Apply this diff to clean up the code:

      const { ...rest } = res2.body;
      expect(res2).to.have.status(200);
      expect(rest).to.be.deep.equal(popup().build());
-      // expect(creator.id).to.be.equal(user().build().id);

486-497: Improve test data setup readability.

The test data setup using Promise.all with map could be more readable using a more descriptive approach.

Consider refactoring to improve readability:

-      await Promise.all(
-        popupList.map((popup) => {
-          return chai.request
-            .execute(app)
-            .post("/api/popup/add_popup")
-            .set(
-              "Authorization",
-              `Bearer ${popup.createdBy === 1 ? token : newToken}`
-            )
-            .send(popup);
-        })
-      );
+      const createPopup = async (popup) => {
+        const authToken = popup.createdBy === 1 ? token : newToken;
+        return chai.request
+          .execute(app)
+          .post("/api/popup/add_popup")
+          .set("Authorization", `Bearer ${authToken}`)
+          .send(popup);
+      };
+      
+      await Promise.all(popupList.map(createPopup));
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6778058 and da4babc.

📒 Files selected for processing (2)
  • backend/src/test/e2e/popup.test.mjs (18 hunks)
  • backend/src/test/unit/controllers/popup.test.js (22 hunks)

@Anurag9977 Anurag9977 requested a review from erenfn February 24, 2025 10:42
Copy link
Collaborator

@erenfn erenfn left a comment

Choose a reason for hiding this comment

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

Looks good

@erenfn erenfn merged commit 458e104 into bluewave-labs:develop Feb 24, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants