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

refactoring the createValidateSelectedSitesField middleware function #3658

Merged
merged 3 commits into from
Oct 15, 2024

Conversation

Baalmart
Copy link
Contributor

@Baalmart Baalmart commented Oct 15, 2024

Description

Refactoring the createValidateSelectedSitesField middleware function to add one edge case and also refactornig the validateUniqueFieldsInSelectedSites middleware function to only consider fields that are present in the input objects.

Changes Made

  • New Parameter: Added a second parameter allowId to the middleware function. This boolean parameter determines whether the _id field is permitted.
  • Conditional Check: The check for the _id field now depends on the allowId parameter. If allowId is false, the middleware will throw an error when _id is present.
  • Conditional Checks: Each field is checked for existence (!== undefined) before checking for duplicates. This ensures that only provided fields are considered.
  • Maintained Original Logic: The logic to track duplicates and prepare error messages remains intact, ensuring that the middleware continues to function as intended while being more flexible with input.

Testing

  • Tested locally
  • Tested against staging environment
  • Relevant tests passed: [List test names]

Affected Services

  • Which services were modified:
    • Auth Service

Endpoints Ready for Testing

  • New endpoints ready for testing:
    • All endpoints for User Preferences
    • All endpoints for Default User Preferences

API Documentation Updated?

  • Yes, API documentation was updated
  • No, API documentation does not need updating

Additional Notes

When using this middleware in your route definitions, you can specify whether to allow the _id field:

  • app.post('/route-allowing-id', createValidateSelectedSitesField(['name', 'site_id'], true));
  • app.post('/route-not-allowing-id', createValidateSelectedSitesField(['name', 'site_id'], false));

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced validation for selected_sites in various routes to conditionally handle the presence of _id fields.
    • Introduced middleware to check for duplicates in the selected_sites array, ensuring unique entries.
  • Bug Fixes

    • Improved error handling for invalid _id presence based on the new validation logic.

Copy link
Contributor

coderabbitai bot commented Oct 15, 2024

Caution

Review failed

The pull request is closed.

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request enhance the validation logic in the src/auth-service/routes/v2/preferences.js file, specifically for the selected_sites field across various routes. The createValidateSelectedSitesField function now accepts an allowId parameter to conditionally manage the presence of an _id field. Additionally, a new middleware function, validateUniqueFieldsInSelectedSites, has been introduced to ensure the uniqueness of site IDs and names within the selected_sites array. These modifications aim to improve the validation mechanisms for incoming requests.

Changes

File Path Change Summary
src/auth-service/routes/v2/preferences.js - Updated createValidateSelectedSitesField to accept allowId parameter.
- Adjusted validation for selected_sites in POST, PATCH, PUT, DELETE routes to utilize the new parameter.
- Introduced validateUniqueFieldsInSelectedSites middleware to check for duplicates in selected_sites.

Possibly related issues

Possibly related PRs

Suggested reviewers

  • Codebmk
  • BenjaminSsempala
  • OchiengPaul442

🎉 "In the realm of code where validations reign,
New logic emerges, enhancing the chain.
With checks for uniqueness, we strive to ensure,
That selected_sites are tidy and pure.
A sprinkle of parameters, a middleware delight,
In the world of preferences, everything's right!" 🎉


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 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
Contributor

Auth-service changes in this PR available for preview here

Copy link

codecov bot commented Oct 15, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 27.04%. Comparing base (6cc3646) to head (76b925c).
Report is 4 commits behind head on staging.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           staging    #3658   +/-   ##
========================================
  Coverage    27.04%   27.04%           
========================================
  Files          146      146           
  Lines        21339    21339           
  Branches       274      274           
========================================
  Hits          5772     5772           
  Misses       15567    15567           

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

🧹 Outside diff range and nitpick comments (1)
src/auth-service/routes/v2/preferences.js (1)

Line range hint 119-214: Add validation for 'selectedSites' in 'validateUniqueFieldsInSelectedSites'

To avoid potential runtime errors when selectedSites is undefined or not an array, ensure that a validation check is in place. This will enhance the robustness of the middleware.

Consider adding the following check at the start of the function:

const validateUniqueFieldsInSelectedSites = (req, res, next) => {
  const selectedSites = req.body.selected_sites;
+ if (!Array.isArray(selectedSites) || selectedSites.length === 0) {
+   return res.status(400).json({
+     success: false,
+     message: "selected_sites must be a non-empty array",
+   });
+ }

  // Create Sets to track unique values for each field
  const uniqueSiteIds = new Set();
  // ...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6cc3646 and 84acb71.

📒 Files selected for processing (1)
  • src/auth-service/routes/v2/preferences.js (8 hunks)
🧰 Additional context used
🔇 Additional comments (3)
src/auth-service/routes/v2/preferences.js (3)

382-382: Verify the use of 'allowId' parameter set to true

In the calls to createValidateSelectedSitesField, the allowId parameter is set to true, allowing the _id field. Please confirm that this behavior is intended and consistent with the application requirements.

Also applies to: 584-584, 787-787, 957-957


1188-1191: Validation logic for 'selected_sites' conforms to requirements

The use of createValidateSelectedSitesField with required fields ["site_id", "search_name", "name"] and allowId set to false appropriately restricts the _id field. The implementation aligns with the intended validation rules.


1227-1227: Clarify the use of empty 'requiredFields' array

An empty array is passed as requiredFields to createValidateSelectedSitesField. Ensure that no required fields are necessary in this context and that the function handles this scenario correctly.

Comment on lines 32 to 37
function createValidateSelectedSitesField(requiredFields, allowId = false) {
return function (value) {
// Edge case: Check if _id field is present
if (!allowId && "_id" in value) {
throw new Error("_id field is not allowed");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure 'value' is not null or undefined before checking '_id' field

To prevent potential runtime errors, consider adding a check to ensure that value is not null or undefined before accessing its properties. This will safeguard against situations where value might be missing.

Apply this diff to include the null check:

function createValidateSelectedSitesField(requiredFields, allowId = false) {
  return function (value) {
+   if (!value) {
+     throw new Error("Value must not be null or undefined");
+   }
    // Edge case: Check if _id field is present
    if (!allowId && "_id" in value) {
      throw new Error("_id field is not allowed");
    }
📝 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
function createValidateSelectedSitesField(requiredFields, allowId = false) {
return function (value) {
// Edge case: Check if _id field is present
if (!allowId && "_id" in value) {
throw new Error("_id field is not allowed");
}
function createValidateSelectedSitesField(requiredFields, allowId = false) {
return function (value) {
if (!value) {
throw new Error("Value must not be null or undefined");
}
// Edge case: Check if _id field is present
if (!allowId && "_id" in value) {
throw new Error("_id field is not allowed");
}

…any fields that are not present in the input objects
Copy link
Contributor

Auth-service changes in this PR available for preview here

…lue is not null or undefined before accessing its properties
Copy link
Contributor

Auth-service changes in this PR available for preview here

@Baalmart Baalmart merged commit c20a8e8 into staging Oct 15, 2024
50 checks passed
@Baalmart Baalmart deleted the en-validation branch October 15, 2024 18:04
@Baalmart Baalmart mentioned this pull request Oct 15, 2024
1 task
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 84acb71 and c53a557.

📒 Files selected for processing (1)
  • src/auth-service/routes/v2/preferences.js (10 hunks)
🧰 Additional context used
🔇 Additional comments (1)
src/auth-service/routes/v2/preferences.js (1)

1195-1198: Review the allowId parameter usage

In this instance, allowId is set to false, but _id is not included in the required fields. Ensure this is intentional and that _id should indeed be disallowed in this context.

If _id should be allowed, consider setting allowId to true. If it should be required, include it in the requiredFields array.

@@ -1214,7 +1231,7 @@ router.put(
return ObjectId(value);
}),
body("selected_site")
.custom(createValidateSelectedSitesField([]))
.custom(createValidateSelectedSitesField([], false))
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Specify required fields when using createValidateSelectedSitesField

Currently, createValidateSelectedSitesField is called with an empty array for requiredFields. This may lead to unintended behavior since no fields are being validated as required. Please specify the required fields to ensure proper validation.

For example:

.custom(createValidateSelectedSitesField(
-  [],
+  ['search_name', 'name'],
  false
))

Committable suggestion was skipped due to low confidence.

Comment on lines +133 to +157
// Check for duplicate site_id if it exists
if (item.site_id !== undefined) {
if (uniqueSiteIds.has(item.site_id)) {
duplicateSiteIds.push(item.site_id);
} else {
uniqueSiteIds.add(item.site_id);
}
}

// Check for duplicate search_name
if (uniqueSearchNames.has(item.search_name)) {
duplicateSearchNames.push(item.search_name);
} else {
uniqueSearchNames.add(item.search_name);
// Check for duplicate search_name if it exists
if (item.search_name !== undefined) {
if (uniqueSearchNames.has(item.search_name)) {
duplicateSearchNames.push(item.search_name);
} else {
uniqueSearchNames.add(item.search_name);
}
}

// Check for duplicate name
if (uniqueNames.has(item.name)) {
duplicateNames.push(item.name);
} else {
uniqueNames.add(item.name);
// Check for duplicate name if it exists
if (item.name !== undefined) {
if (uniqueNames.has(item.name)) {
duplicateNames.push(item.name);
} else {
uniqueNames.add(item.name);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor duplicate code in validateUniqueFieldsInSelectedSites

The function contains repetitive code blocks for checking duplicates of site_id, search_name, and name. Consider refactoring this logic to reduce code duplication and enhance maintainability.

Here's a suggested refactor:

const validateUniqueFieldsInSelectedSites = (req, res, next) => {
  const selectedSites = req.body.selected_sites;

  // Fields to check for duplicates
+ const fieldsToCheck = ['site_id', 'search_name', 'name'];
+ const uniqueFields = {};
+ const duplicateFields = {};

+ // Initialize Sets for each field
+ fieldsToCheck.forEach((field) => {
+   uniqueFields[field] = new Set();
+   duplicateFields[field] = new Set();
+ });

  selectedSites.forEach((item) => {
+   fieldsToCheck.forEach((field) => {
+     if (item[field] !== undefined) {
+       if (uniqueFields[field].has(item[field])) {
+         duplicateFields[field].add(item[field]);
+       } else {
+         uniqueFields[field].add(item[field]);
+       }
+     }
+   });
  });

  // Prepare error messages based on duplicates found
  let errorMessage = "";
+ fieldsToCheck.forEach((field) => {
+   if (duplicateFields[field].size > 0) {
+     errorMessage +=
+       `Duplicate ${field}s found: ${[...duplicateFields[field]].join(", ")}. `;
+   }
+ });

  // If any duplicates were found, respond with an error
  if (errorMessage) {
    return res.status(400).json({
      success: false,
      message: errorMessage.trim(),
    });
  }

  next();
};
📝 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
// Check for duplicate site_id if it exists
if (item.site_id !== undefined) {
if (uniqueSiteIds.has(item.site_id)) {
duplicateSiteIds.push(item.site_id);
} else {
uniqueSiteIds.add(item.site_id);
}
}
// Check for duplicate search_name
if (uniqueSearchNames.has(item.search_name)) {
duplicateSearchNames.push(item.search_name);
} else {
uniqueSearchNames.add(item.search_name);
// Check for duplicate search_name if it exists
if (item.search_name !== undefined) {
if (uniqueSearchNames.has(item.search_name)) {
duplicateSearchNames.push(item.search_name);
} else {
uniqueSearchNames.add(item.search_name);
}
}
// Check for duplicate name
if (uniqueNames.has(item.name)) {
duplicateNames.push(item.name);
} else {
uniqueNames.add(item.name);
// Check for duplicate name if it exists
if (item.name !== undefined) {
if (uniqueNames.has(item.name)) {
duplicateNames.push(item.name);
} else {
uniqueNames.add(item.name);
}
const validateUniqueFieldsInSelectedSites = (req, res, next) => {
const selectedSites = req.body.selected_sites;
// Fields to check for duplicates
const fieldsToCheck = ['site_id', 'search_name', 'name'];
const uniqueFields = {};
const duplicateFields = {};
// Initialize Sets for each field
fieldsToCheck.forEach((field) => {
uniqueFields[field] = new Set();
duplicateFields[field] = new Set();
});
selectedSites.forEach((item) => {
fieldsToCheck.forEach((field) => {
if (item[field] !== undefined) {
if (uniqueFields[field].has(item[field])) {
duplicateFields[field].add(item[field]);
} else {
uniqueFields[field].add(item[field]);
}
}
});
});
// Prepare error messages based on duplicates found
let errorMessage = "";
fieldsToCheck.forEach((field) => {
if (duplicateFields[field].size > 0) {
errorMessage +=
`Duplicate ${field}s found: ${[...duplicateFields[field]].join(", ")}. `;
}
});
// If any duplicates were found, respond with an error
if (errorMessage) {
return res.status(400).json({
success: false,
message: errorMessage.trim(),
});
}
next();
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant