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

fixing runtime when upserting prefereces #4069

Merged
merged 2 commits into from
Dec 13, 2024
Merged

fixing runtime when upserting prefereces #4069

merged 2 commits into from
Dec 13, 2024

Conversation

Baalmart
Copy link
Contributor

@Baalmart Baalmart commented Dec 13, 2024

Description

fixing runtime when upserting prefereces

Changes Made

  • fixing runtime when upserting prefereces

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:
    • Upsert Preference
    • Replace Preference

API Documentation Updated?

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

Additional Notes

fixing runtime when upserting prefereces

Summary by CodeRabbit

  • New Features

    • Enhanced validation for user and group associations during preference updates.
    • Improved handling of array fields and ObjectId processing in preference management.
  • Bug Fixes

    • Streamlined error handling for various methods to ensure accurate HTTP responses.
    • Added checks for empty strings in ObjectId processing.
  • Documentation

    • Updated method signatures for clarity, reflecting changes in logic.

Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request primarily focus on the Preference.js model and the create-preference.js utility in the src/auth-service directory. Enhancements include improved validation and processing of ObjectId fields, a refined pre-save hook, and better error handling in various methods. The update logic for preferences has been streamlined, ensuring robust validation of user and group associations. Overall, the modifications aim to enhance the clarity and reliability of preference management functionality.

Changes

File Path Change Summary
src/auth-service/models/Preference.js Refactored pre-save hook to categorize ID fields, updated processObjectId to handle empty strings, set default values only when creating new documents, and refined error handling in register, modify, and remove.
src/auth-service/utils/create-preference.js Enhanced validateUserAndGroup for user and group role checks, improved prepareUpdate for handling $addToSet, streamlined update methods, and improved error handling across various methods.

Possibly related PRs

Suggested reviewers

  • Codebmk
  • OchiengPaul442
  • BenjaminSsempala

🎉 In the realm of code where preferences dwell,
Validation and logic weave a fine spell.
With hooks and checks, we tidy the flow,
Ensuring each ID and user can grow.
So here's to the changes, both clear and bright,
Enhancing our service, making it 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 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
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: 4

🧹 Outside diff range and nitpick comments (3)
src/auth-service/utils/create-preference.js (3)

Line range hint 214-228: Correct usage of filter instead of filterResponse.

The variable filterResponse is not defined in this context. You likely intended to use filter, which is defined earlier.

Apply this diff to rectify the variable name:

       const filter = generateFilter.preferences(request, next);
-      if (isEmpty(filterResponse) || isEmpty(filterResponse.user_id)) {
+      if (isEmpty(filter) || isEmpty(filter.user_id)) {
         next(
           new HttpError(
             "Internal Server Error",
             httpStatus.INTERNAL_SERVER_ERROR,
             {
               message:
                 "Unable to obtain the corresponding identifier associated with this preference --- please reach out to [email protected]",
             }
           )
         );
       }

228-228: Ensure prepareUpdate is error-free or handle exceptions.

While prepareUpdate is a custom function, it's prudent to handle any potential errors it might throw to prevent unexpected runtime issues.

Consider wrapping the call in a try-catch block or ensuring that prepareUpdate handles exceptions internally.


336-362: Refactor duplicate code in replace and update methods.

The replace method contains code that's nearly identical to the update method, specifically in validation and field definitions. Refactoring this common logic into shared functions will improve maintainability and reduce redundancy.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d8cdae1 and eb7574d.

📒 Files selected for processing (2)
  • src/auth-service/models/Preference.js (3 hunks)
  • src/auth-service/utils/create-preference.js (5 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/auth-service/utils/create-preference.js

[error] 87-87: field is assigned to itself.

This is where is assigned.

(lint/correctness/noSelfAssign)

🔇 Additional comments (1)
src/auth-service/models/Preference.js (1)

Line range hint 237-243: Validate empty strings in processObjectId function.

Adding a check for empty strings in the processObjectId function enhances robustness by preventing invalid ObjectIds. This ensures that fields with empty strings are set to null, avoiding potential errors during database operations.

Comment on lines 187 to 195
// Validate user and group
const validationError = await validateUserAndGroup(
tenant,
body.user_id,
body.group_id,
next
);
if (validationError) return;

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

Simplify error handling after validateUserAndGroup call.

The validateUserAndGroup function handles errors internally and does not return a value. Therefore, checking validationError is unnecessary since it will always be undefined.

Consider removing the unnecessary variable and condition:

-      const validationError = await validateUserAndGroup(
+      await validateUserAndGroup(
         tenant,
         body.user_id,
         body.group_id,
         next
       );
-      if (validationError) return;
📝 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
// Validate user and group
const validationError = await validateUserAndGroup(
tenant,
body.user_id,
body.group_id,
next
);
if (validationError) return;
// Validate user and group
await validateUserAndGroup(
tenant,
body.user_id,
body.group_id,
next
);

Comment on lines 83 to 89
const singleObjectIdFields = ["user_id", "group_id"];
singleObjectIdFields.forEach((field) => {
if (update[field]) {
// Keep the original value for simple ObjectId fields
update[field] = update[field];
}
});
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

Remove unnecessary self-assignment of update[field].

Assigning update[field] to itself on line 87 is redundant and has no effect. Removing this line will clean up the code without altering functionality.

Apply this diff to eliminate the redundant assignment:

       if (update[field]) {
-        // Keep the original value for simple ObjectId fields
-        update[field] = update[field];
       }
📝 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 singleObjectIdFields = ["user_id", "group_id"];
singleObjectIdFields.forEach((field) => {
if (update[field]) {
// Keep the original value for simple ObjectId fields
update[field] = update[field];
}
});
const singleObjectIdFields = ["user_id", "group_id"];
singleObjectIdFields.forEach((field) => {
if (update[field]) {
}
});
🧰 Tools
🪛 Biome (1.9.4)

[error] 87-87: field is assigned to itself.

This is where is assigned.

(lint/correctness/noSelfAssign)

Comment on lines 403 to 414
selectedArrayFields.forEach((field) => {
if (updateData[field]) {
updateData[field] = updateData[field].map(
selectedArrayProcessors[field]
);

// Use $addToSet for selected arrays
updateData.$addToSet = updateData.$addToSet || {};
updateData.$addToSet[field] = {
$each: updateData[field],
};
delete updateData[field];
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

Prevent overwriting of $addToSet in selected arrays processing.

When processing selectedArrayFields, directly assigning to updateData.$addToSet may overwrite existing entries. To avoid this, merge new fields into $addToSet without replacing existing ones.

Modify the code to merge fields:

           // Use $addToSet for selected arrays
-          updateData.$addToSet = updateData.$addToSet || {};
-          updateData.$addToSet[field] = {
+          updateData.$addToSet = {
+            ...updateData.$addToSet,
+            [field]: {
               $each: updateData[field],
             },
           };
           delete updateData[field];
📝 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
selectedArrayFields.forEach((field) => {
if (updateData[field]) {
updateData[field] = updateData[field].map(
selectedArrayProcessors[field]
);
// Use $addToSet for selected arrays
updateData.$addToSet = updateData.$addToSet || {};
updateData.$addToSet[field] = {
$each: updateData[field],
};
delete updateData[field];
selectedArrayFields.forEach((field) => {
if (updateData[field]) {
updateData[field] = updateData[field].map(
selectedArrayProcessors[field]
);
// Use $addToSet for selected arrays
updateData.$addToSet = {
...updateData.$addToSet,
[field]: {
$each: updateData[field],
},
};
delete updateData[field];

Comment on lines 418 to 425
// Process array ID fields
arrayIdFields.forEach((field) => {
if (updateData[field]) {
updateData.$addToSet = updateData.$addToSet || {};
updateData.$addToSet[field] = {
$each: updateData[field],
$each: Array.isArray(updateData[field])
? updateData[field].map(processObjectId)
: [processObjectId(updateData[field])],
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 $addToSet merges existing array ID fields.

Similar to the previous issue, when adding array ID fields to $addToSet, ensure you merge with existing fields to prevent overwriting.

Update the code as follows:

           if (updateData[field]) {
-            updateData.$addToSet = updateData.$addToSet || {};
-            updateData.$addToSet[field] = {
+            updateData.$addToSet = {
+              ...updateData.$addToSet,
+              [field]: {
                 $each: Array.isArray(updateData[field])
                   ? updateData[field].map(processObjectId)
                   : [processObjectId(updateData[field])],
               },
             };
             delete updateData[field];
           }
📝 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
// Process array ID fields
arrayIdFields.forEach((field) => {
if (updateData[field]) {
updateData.$addToSet = updateData.$addToSet || {};
updateData.$addToSet[field] = {
$each: updateData[field],
$each: Array.isArray(updateData[field])
? updateData[field].map(processObjectId)
: [processObjectId(updateData[field])],
// Process array ID fields
arrayIdFields.forEach((field) => {
if (updateData[field]) {
updateData.$addToSet = {
...updateData.$addToSet,
[field]: {
$each: Array.isArray(updateData[field])
? updateData[field].map(processObjectId)
: [processObjectId(updateData[field])],
},
};

Copy link

codecov bot commented Dec 13, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 11.81%. Comparing base (30795ee) to head (666c098).
Report is 64 commits behind head on staging.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           staging    #4069   +/-   ##
========================================
  Coverage    11.81%   11.81%           
========================================
  Files          115      115           
  Lines        15482    15482           
  Branches       319      319           
========================================
  Hits          1829     1829           
  Misses       13653    13653           

Copy link
Contributor

Auth-service changes in this PR available for preview here

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 and nitpick comments (2)
src/auth-service/models/Preference.js (2)

Line range hint 237-244: Enhance ObjectId validation robustness.

Consider improving the ObjectId validation with these enhancements:

 if (!id) return null;
 if (id instanceof mongoose.Types.ObjectId) return id;
-if (typeof id === "string" && id.trim() === "") return null;
+if (typeof id === "string") {
+  const trimmed = id.trim();
+  if (trimmed === "") return null;
+  if (!ObjectId.isValid(trimmed)) {
+    throw new Error(`Invalid ObjectId format: ${id}`);
+  }
+  return mongoose.Types.ObjectId(trimmed);
+}
-try {
-  return mongoose.Types.ObjectId(id);
-} catch (error) {
-  logger.error(`Invalid ObjectId: ${id}`);
-  throw new Error(`Invalid ObjectId: ${id}`);
-}
+throw new Error(`Invalid ObjectId type: expected string or ObjectId, got ${typeof id}`);

420-432: Consider optimizing array field processing.

The current implementation processes each array field separately. Consider combining similar operations to reduce code duplication and improve maintainability.

-arrayIdFields.forEach((field) => {
-  if (updateData[field]) {
-    updateData.$addToSet = {
-      ...updateData.$addToSet,
-      [field]: {
-        $each: Array.isArray(updateData[field])
-          ? updateData[field].map(processObjectId)
-          : [processObjectId(updateData[field])],
-      },
-    };
-    delete updateData[field];
-  }
-});
+const processArrayFields = (fields) => {
+  const updates = fields.reduce((acc, field) => {
+    if (updateData[field]) {
+      acc[field] = {
+        $each: Array.isArray(updateData[field])
+          ? updateData[field].map(processObjectId)
+          : [processObjectId(updateData[field])]
+      };
+      delete updateData[field];
+    }
+    return acc;
+  }, {});
+  
+  if (Object.keys(updates).length > 0) {
+    updateData.$addToSet = {
+      ...updateData.$addToSet,
+      ...updates
+    };
+  }
+};
+
+processArrayFields(arrayIdFields);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eb7574d and 666c098.

📒 Files selected for processing (2)
  • src/auth-service/models/Preference.js (3 hunks)
  • src/auth-service/utils/create-preference.js (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/auth-service/utils/create-preference.js
🔇 Additional comments (3)
src/auth-service/models/Preference.js (3)

246-270: Well-structured field categorization!

The separation of fields into singleIdFields, arrayIdFields, and selectedArrayFields improves code organization and maintainability.


409-416: Fixed: Proper merging of $addToSet operations.

The implementation now correctly merges $addToSet operations without overwriting existing entries.


Line range hint 1-24: Verify impact on existing preferences.

The changes to preference processing logic could affect existing preferences. Let's verify the current usage patterns:

✅ Verification successful

Let me analyze the actual usage patterns and validation logic to better understand the impact of these changes on existing preferences.


No impact on existing preferences detected

Based on the comprehensive analysis of the codebase:

  • The changes only add mongoose schema definition and validation
  • Existing preference update operations use findOneAndUpdate with proper validation
  • The periodSchema is consistently used across preference-related models
  • The schema changes maintain backward compatibility with existing data structure

The modifications enhance data validation without breaking existing preference processing patterns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for existing preferences that might be affected by the new validation
echo "Checking for potential validation issues in existing code..."

# Search for direct ObjectId assignments
rg -l "new ObjectId\(|Types\.ObjectId\(" --type js

# Search for preference update patterns
ast-grep --pattern 'findOneAndUpdate($$$, { $$$: $_ }, $$$)'

# Look for any custom validation logic
rg "validate.*preference" --type js

Length of output: 1501


Script:

#!/bin/bash
# Let's check for preference-related operations more comprehensively

# Check for preference schema usage and validation
rg "PreferenceSchema|periodSchema" -B 2 -A 2 --type js

# Look for preference update operations
rg "updatePreference|update.*preference" -i --type js

# Check for preference-related API endpoints
rg "router\.(post|put|patch).*preference" -i --type js

# Search for preference-related tests
fd "test" -e js -x rg "preference" -i {} \;

Length of output: 6616

Copy link
Contributor

Auth-service changes in this PR available for preview here

@Baalmart Baalmart merged commit 05a9f5e into staging Dec 13, 2024
52 checks passed
@Baalmart Baalmart deleted the hf-prefs-updates branch December 13, 2024 13:44
@Baalmart Baalmart mentioned this pull request Dec 13, 2024
1 task
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