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

389 refactoring validations in hint routes with express validator #490

Merged

Conversation

DeboraSerra
Copy link
Contributor

Describe your changes

Update the code to use the validation middleware instead of foing the validations in the controller for the Hint.

image

Issue number

#389

Please ensure all items are checked off before requesting a review:

  • I deployed the code locally.
  • I have performed a self-review of my code.
  • I have included the issue # in the PR.
  • I have labelled the PR correctly.
  • The issue I am working on is assigned to me.
  • I didn't use any hardcoded values (otherwise it will not scale, and will make it difficult to maintain consistency across the application).
  • I made sure font sizes, color choices etc are all referenced from the theme.
  • My PR is granular and targeted to one specific feature.
  • I took a screenshot or a video and attached to this PR if there is a UI change.

@DeboraSerra DeboraSerra requested a review from erenfn January 14, 2025 22:05
Copy link
Contributor

coderabbitai bot commented Jan 14, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces significant changes to hint-related functionality across the backend and frontend. The modifications primarily focus on restructuring validation mechanisms, removing strict input checks, and updating error handling approaches. The changes span multiple files including controllers, routes, validators, tests, and frontend components, with a consistent theme of simplifying validation and error management for hint-related operations.

Changes

File Change Summary
backend/src/controllers/hint.controller.js Removed validation checks in methods like addHint and updateHint. Updated error messages to use single quotes.
backend/src/routes/hint.routes.js Added validation middleware for routes. Applied authenticateJWT and accessGuard globally.
backend/src/test/e2e/hint.test.mjs Converted string literals from double to single quotes.
backend/src/test/unit/controllers/hint.test.js Removed test cases checking for invalid inputs and parameter validations.
backend/src/utils/hint.helper.js Replaced validateHintData with new validators: hintValidator, paramIdValidator, and bodyUrlValidator.
frontend/src/scenes/hints/CreateHintPage.jsx Updated import formatting, error handling, and string literals.
backend/src/test/mocks/hint.mock.js Updated HintBuilder with new default values for hint properties.

Possibly related PRs

Suggested Labels

enhancement, design

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 33cb1b7 and 1f4d8a5.

📒 Files selected for processing (1)
  • frontend/src/scenes/hints/CreateHintPage.jsx (4 hunks)

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: 3

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

4-4: Let's make those valid actions more maintainable!

Consider moving the validActions array to a separate configuration file to make it easier to maintain and reuse.

Create a new file config/constants.js:

exports.HINT_ACTIONS = ['no action', 'open url', 'open url in a new tab'];

Then import and use it:

- const validActions = ['no action', 'open url', 'open url in a new tab'];
+ const { HINT_ACTIONS } = require('../config/constants');

15-31: These color validations got me losing myself in the repetition!

The color validation logic is repeated for multiple fields. Let's DRY this up!

Create a reusable color validator:

+ const colorValidator = (fieldName) => 
+   body(fieldName)
+     .optional()
+     .isString()
+     .custom(isValidHexColor)
+     .withMessage(`Invalid value for ${fieldName}`);

const hintValidator = [
  body('action')
    .isString()
    .notEmpty()
    .withMessage('action is required')
    .custom((value) => {
-     return validActions.includes(value);
+     return HINT_ACTIONS.includes(value);
    })
    .withMessage('Invalid value for action'),
-  body('headerBackgroundColor')
-    .optional()
-    .isString()
-    .custom(isValidHexColor)
-    .withMessage('Invalid value for headerBackgroundColor'),
+  colorValidator('headerBackgroundColor'),
-  body('headerColor').optional().isString().custom(isValidHexColor).withMessage('Invalid value for headerColor'),
+  colorValidator('headerColor'),
-  body('textColor').optional().isString().custom(isValidHexColor).withMessage('Invalid value for textColor'),
+  colorValidator('textColor'),
-  body('buttonBackgroundColor')
-    .optional()
-    .isString()
-    .custom(isValidHexColor)
-    .withMessage('Invalid value for buttonBackgroundColor'),
+  colorValidator('buttonBackgroundColor'),
-  body('buttonTextColor')
-    .optional()
-    .isString()
-    .custom(isValidHexColor)
-    .withMessage('Invalid value for buttonTextColor'),
+  colorValidator('buttonTextColor'),
];
frontend/src/scenes/hints/CreateHintPage.jsx (1)

28-32: These states got my palms sweaty! Let's clean them up! 💦

Multiple color-related states with hardcoded default values could be more maintainable.

Consider using a configuration object:

const DEFAULT_COLORS = {
  headerBackground: '#FFFFFF',
  header: '#101828',
  text: '#344054',
  buttonBackground: '#7F56D9',
  buttonText: '#FFFFFF'
};

// Then use it in your component:
const [colors, setColors] = useState(DEFAULT_COLORS);

// Update individual colors:
setColors(prev => ({ ...prev, headerBackground: newColor }));
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f177ef3 and d565c98.

📒 Files selected for processing (6)
  • backend/src/controllers/hint.controller.js (10 hunks)
  • backend/src/routes/hint.routes.js (1 hunks)
  • backend/src/test/e2e/hint.test.mjs (8 hunks)
  • backend/src/test/unit/controllers/hint.test.js (0 hunks)
  • backend/src/utils/hint.helper.js (1 hunks)
  • frontend/src/scenes/hints/CreateHintPage.jsx (4 hunks)
💤 Files with no reviewable changes (1)
  • backend/src/test/unit/controllers/hint.test.js
✅ Files skipped from review due to trivial changes (1)
  • backend/src/test/e2e/hint.test.mjs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (22.x)
🔇 Additional comments (2)
backend/src/routes/hint.routes.js (1)

18-24: Validation middleware looking clean, mom's spaghetti! 🍝

Solid implementation of validation middleware chains. Each route has appropriate validators for its parameters and request body.

backend/src/controllers/hint.controller.js (1)

17-19: Error handling's looking clean, better than mom's spaghetti! 🍝

Consistent error handling pattern across all controller methods using the error helper.

Also applies to: 33-35, 47-49, 70-72, 95-97, 120-122

backend/src/routes/hint.routes.js Outdated Show resolved Hide resolved
backend/src/controllers/hint.controller.js Outdated Show resolved Hide resolved
frontend/src/scenes/hints/CreateHintPage.jsx Outdated Show resolved Hide resolved
@DeboraSerra DeboraSerra linked an issue Jan 15, 2025 that may be closed by this pull request
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

🧹 Nitpick comments (2)
backend/src/utils/hint.helper.js (2)

1-5: Yo dawg, let's make these valid actions more maintainable!

Consider moving validActions to a separate constants/config file. This would make it easier to maintain and reuse across the codebase.

- const validActions = ['no action', 'open url', 'open url in a new tab'];
+ const { HINT_ACTIONS } = require('../constants/hint.constants');

47-49: Knees weak, arms heavy, this ID validation needs to be more steady!

Consider adding bounds checking for the hintId to prevent potential integer overflow issues.

  param('hintId')
    .notEmpty()
    .withMessage('hintId is required')
    .isInt()
+   .isInt({ min: 1 })
    .withMessage('Invalid hint ID'),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b2b747f and 15847f2.

📒 Files selected for processing (1)
  • backend/src/utils/hint.helper.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (22.x)
🔇 Additional comments (1)
backend/src/utils/hint.helper.js (1)

53-53: Clean exports, just like mom's spaghetti! 🍝

The export statement is clean and follows best practices.

backend/src/utils/hint.helper.js Show resolved Hide resolved
backend/src/utils/hint.helper.js Outdated Show resolved Hide resolved
body('headerColor').optional().isString().custom(isValidHexColor).withMessage('Invalid value for headerColor'),
body('textColor').optional().isString().custom(isValidHexColor).withMessage('Invalid value for textColor'),
body('buttonBackgroundColor')
.optional()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Are colors optional?

Copy link
Contributor Author

@DeboraSerra DeboraSerra Jan 15, 2025

Choose a reason for hiding this comment

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

The original code was set as optional... I believe they have a default value...

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.

onboarding_backend-1  | CREATE_HINT_ERROR: Error creating hint: Validation error: Validation isIn on tooltipPlacement failed
onboarding_backend-1  | CREATE_HINT_ERROR: Error creating hint: notNull Violation: Hint.tooltipPlacement cannot be null

Not null condition is not checked

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 (3)
backend/src/utils/hint.helper.js (3)

5-5: Yo! Let's freeze that array like mom's spaghetti!

Consider freezing the validActions array to prevent accidental modifications:

-const validActions = ['no action', 'open url', 'open url in a new tab'];
+const validActions = Object.freeze(['no action', 'open url', 'open url in a new tab']);

11-18: Yo! These error messages are all over the place like spilled spaghetti!

Let's make the error messages consistent with the format "Invalid value for...":

   body('action')
     .isString()
     .notEmpty()
-    .withMessage('action is required')
+    .withMessage('Invalid value: action is required')
     .custom((value) => {
       return validActions.includes(value);
     })
     .withMessage('Invalid value for action'),

48-50: Let's convert that ID like we convert raw spaghetti to cooked!

Consider adding type conversion to ensure the hint ID is always a number:

   param('hintId')
     .notEmpty()
     .withMessage('hintId is required')
     .isInt()
+    .toInt()
     .withMessage('Invalid hint ID'),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 15847f2 and ba010be.

📒 Files selected for processing (4)
  • backend/src/test/e2e/auth.test.mjs (3 hunks)
  • backend/src/test/e2e/hint.test.mjs (8 hunks)
  • backend/src/test/mocks/hint.mock.js (1 hunks)
  • backend/src/utils/hint.helper.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/test/e2e/hint.test.mjs
🧰 Additional context used
🪛 Biome (1.9.4)
backend/src/test/e2e/auth.test.mjs

[error] 11-11: Don't focus the test.

The 'only' method is often used for debugging or during implementation. It should be removed before deploying to production.
Consider removing 'only' to ensure all tests are executed.
Unsafe fix: Remove focus from test.

(lint/suspicious/noFocusedTests)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (22.x)
🔇 Additional comments (3)
backend/src/utils/hint.helper.js (2)

7-8: Neat DRY implementation, better than mom's dry spaghetti!

The color validator helper function effectively reduces code duplication and maintains consistency.


24-35: Still got inconsistent URL validation - mom's spaghetti would not approve!

The URL validation approach is inconsistent between the hint validator and body validator.

backend/src/test/mocks/hint.mock.js (1)

6-8: These mock updates are as fresh as mom's spaghetti sauce!

The default values added to the hint builder align well with the validation requirements.

Also applies to: 12-12

backend/src/test/e2e/auth.test.mjs Outdated Show resolved Hide resolved
@erenfn erenfn self-requested a review January 16, 2025 02:25
@erenfn erenfn merged commit b4b2401 into develop Jan 16, 2025
1 of 2 checks passed
@erenfn erenfn deleted the 389-refactoring-validations-in-hint-routes-with-express-validator branch January 16, 2025 23:52
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.

Refactoring Validations in hint routes with express-validator
2 participants