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

adding input validations for the devices update routes #3707

Merged
merged 1 commit into from
Oct 21, 2024

Conversation

Baalmart
Copy link
Contributor

@Baalmart Baalmart commented Oct 21, 2024

Description

adding input validations for the devices update routes

Changes Made

  • adding input validations for the devices update routes

Testing

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

Affected Services

  • Which services were modified:
    • Device Registry

Endpoints Ready for Testing

  • New endpoints ready for testing:
    • Update device
    • Soft update device

API Documentation Updated?

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

Additional Notes

adding input validations for the devices update routes

Summary by CodeRabbit

  • New Features

    • Introduced a new category system for devices with options: GAS, LOWCOST, and BAM.
    • Added new fields device_codes and category to device update routes, enhancing data management.
  • Bug Fixes

    • Improved validation logic for device management, ensuring accurate data entry and error handling for new fields.
  • Documentation

    • Updated error messages to provide clearer feedback on validation failures for new fields.

Copy link
Contributor

coderabbitai bot commented Oct 21, 2024

📝 Walkthrough

Walkthrough

The changes introduce a new constant DEVICE_CATEGORIES in the device model, defining three categories: GAS, LOWCOST, and BAM. The category field in the deviceSchema is updated to use this constant, enforcing valid values and setting a default of "lowcost". Additionally, error handling is added to prevent duplicates in the cohorts array. In the device management routes, new validation rules and fields (device_codes and category) are implemented for update operations, enhancing data integrity and user feedback on validation errors.

Changes

File Path Change Summary
src/device-registry/models/Device.js - Added constant DEVICE_CATEGORIES with values GAS, LOWCOST, BAM.
- Updated category field in deviceSchema to use DEVICE_CATEGORIES and set default to "lowcost".
- Added error handling for duplicate values in cohorts during pre save hook.
src/device-registry/routes/v2/devices.js - Introduced new validation rules for device_codes and category in update and soft update routes.
- Added device_codes and category fields to request body for PUT / and PUT /soft routes.
- Enhanced error messages for new fields to improve user feedback on validation failures.

Possibly related PRs

Suggested reviewers

  • NicholasTurner23
  • BenjaminSsempala

🎉 In the realm of devices, new rules take flight,
Categories defined, making data just right.
With codes in the mix and validation so clear,
Our models now shine, bringing joy and good cheer!
So here's to the changes, a toast we shall raise,
For better integrity in all of our ways! 🎊


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

codecov bot commented Oct 21, 2024

Codecov Report

Attention: Patch coverage is 25.00000% with 3 lines in your changes missing coverage. Please review.

Project coverage is 11.59%. Comparing base (cf1bb9e) to head (d9ee6fd).
Report is 2 commits behind head on staging.

Files with missing lines Patch % Lines
src/device-registry/routes/v2/devices.js 0.00% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           staging    #3707   +/-   ##
========================================
  Coverage    11.59%   11.59%           
========================================
  Files          108      108           
  Lines        14871    14875    +4     
  Branches       274      274           
========================================
+ Hits          1724     1725    +1     
- Misses       13147    13150    +3     
Files with missing lines Coverage Δ
src/device-registry/models/Device.js 14.50% <100.00%> (+0.44%) ⬆️
src/device-registry/routes/v2/devices.js 26.77% <0.00%> (-0.65%) ⬇️

Copy link
Contributor

Device registry 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: 1

🧹 Outside diff range and nitpick comments (3)
src/device-registry/models/Device.js (1)

Line range hint 249-257: Excellent addition of duplicate checking for the cohorts array!

The pre-save hook effectively prevents data inconsistency by identifying and handling duplicate values in the cohorts array. The logic is sound and efficient.

To further enhance error handling, consider using a custom error class or the HttpError class that's already imported in this file. This would provide more consistent error handling across the application.

Here's a suggested improvement:

 deviceSchema.pre("save", function(next) {
   // ... (existing code)

   // Check for duplicate values in the grids array
   const duplicateValues = this.cohorts.filter(
     (value, index, self) => self.indexOf(value) !== index
   );
   if (duplicateValues.length > 0) {
-    const error = new Error("Duplicate values found in cohorts array.");
-    return next(error);
+    return next(new HttpError("Bad Request", httpStatus.BAD_REQUEST, {
+      message: "Duplicate values found in cohorts array.",
+      duplicates: duplicateValues
+    }));
   }

   return next();
 });

This change would provide more structured error information and maintain consistency with other error handling in the application.

src/device-registry/routes/v2/devices.js (2)

1046-1062: Excellent addition of validation for device_codes!

The new validation for the device_codes field is a great improvement to ensure data integrity. It correctly checks if the field is an array and not empty when provided.

A small suggestion to enhance code readability:

Consider using the isArray() method instead of a custom function:

 body("device_codes")
   .optional()
-  .custom((value) => {
-    return Array.isArray(value);
-  })
+  .isArray()
   .withMessage("the device_codes should be an array if provided")
   .bail()
   .notEmpty()
   .withMessage("the device_codes should not be empty if provided"),

This change would make the validation more concise and easier to understand at a glance.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 1049-1049: src/device-registry/routes/v2/devices.js#L1049
Added line #L1049 was not covered by tests


1251-1261: Great addition of category validation!

The new validation for the category field is a valuable improvement. It ensures that the field, when provided, is not empty and contains one of the allowed values: "bam", "lowcost", or "gas".

A small suggestion for consistency:

Consider updating the error message to match the case of the allowed values:

 body("category")
   .optional()
   .notEmpty()
   .withMessage("category should not be empty IF provided")
   .bail()
   .trim()
   .toLowerCase()
   .isIn(["bam", "lowcost", "gas"])
   .withMessage(
-    "the category value is not among the expected ones which include: LOWCOST, GAS and BAM"
+    "the category value is not among the expected ones which include: lowcost, gas and bam"
   ),

This change would make the error message consistent with the actual allowed values, which are in lowercase.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cf1bb9e and d9ee6fd.

📒 Files selected for processing (2)
  • src/device-registry/models/Device.js (2 hunks)
  • src/device-registry/routes/v2/devices.js (4 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
src/device-registry/routes/v2/devices.js

[warning] 1049-1049: src/device-registry/routes/v2/devices.js#L1049
Added line #L1049 was not covered by tests


[warning] 1438-1438: src/device-registry/routes/v2/devices.js#L1438
Added line #L1438 was not covered by tests


[warning] 1736-1736: src/device-registry/routes/v2/devices.js#L1736
Added line #L1736 was not covered by tests

🔇 Additional comments (4)
src/device-registry/models/Device.js (3)

37-41: Excellent addition of the DEVICE_CATEGORIES constant!

The use of Object.freeze() ensures immutability, which is a great practice. The categories are well-defined and align perfectly with the PR objectives. The naming convention is consistent and follows best practices.


204-208: Great update to the category field in deviceSchema!

The use of DEVICE_CATEGORIES for the enum property ensures consistency with the defined categories. Setting a default value of "lowcost" is a sensible choice for the most common use case. These changes significantly enhance data integrity by restricting the category field to predefined values.


Line range hint 1-1000: Overall, excellent enhancements to the Device model!

The changes in this file significantly improve data integrity and consistency in the device model. The introduction of the DEVICE_CATEGORIES constant, along with the updated category field in the schema, enhances the robustness of the device update functionality. The addition of duplicate checking in the pre-save hook for the cohorts array adds an extra layer of data validation.

These modifications align perfectly with the PR objectives of implementing input validations for the device update routes. They provide a solid foundation for ensuring data consistency and preventing errors during device updates.

Great job on these improvements!

src/device-registry/routes/v2/devices.js (1)

Line range hint 1046-1752: Summary: Excellent enhancements to input validation

Overall, the changes in this file significantly improve the input validation for device update operations. The new validations for device_codes and category fields are consistently implemented across different routes, enhancing data integrity and providing clearer feedback to API users.

A few points to consider:

  1. The suggested refactorings in previous comments would further improve code maintainability.
  2. The static analysis tool indicates that some of the new lines are not covered by tests.

To address the test coverage issue, please run the following command to identify which specific test files need to be updated:

Once you've identified the relevant test files, consider adding test cases that specifically target the new validations for device_codes and category fields. This will ensure that these important additions are properly tested and maintain high code quality.

Great work on improving the robustness of the device update functionality!

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 1736-1736: src/device-registry/routes/v2/devices.js#L1736
Added line #L1736 was not covered by tests

Comment on lines +1733 to +1752
body("device_codes")
.optional()
.custom((value) => {
return Array.isArray(value);
})
.withMessage("the device_codes should be an array if provided")
.bail()
.notEmpty()
.withMessage("the device_codes should not be empty if provided"),
body("category")
.optional()
.notEmpty()
.withMessage("the category should not be empty if provided")
.bail()
.trim()
.toLowerCase()
.isIn(["bam", "lowcost", "gas"])
.withMessage(
"the category value is not among the expected ones which include: lowcost, bam and gas"
),
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

Consistent validation for soft update route - well done!

The addition of validations for device_codes and category fields in the soft update route is excellent. This ensures consistency across different update operations and improves data integrity.

However, I noticed that these validations are duplicated from the previous update route. To improve maintainability:

Consider extracting these common validations into a separate function or middleware. This would reduce code duplication and make future updates easier. Here's a possible approach:

const validateDeviceUpdateFields = [
  body("device_codes")
    .optional()
    .isArray()
    .withMessage("the device_codes should be an array if provided")
    .bail()
    .notEmpty()
    .withMessage("the device_codes should not be empty if provided"),
  body("category")
    .optional()
    .notEmpty()
    .withMessage("the category should not be empty if provided")
    .bail()
    .trim()
    .toLowerCase()
    .isIn(["bam", "lowcost", "gas"])
    .withMessage(
      "the category value is not among the expected ones which include: lowcost, bam and gas"
    ),
  // ... other common validations
];

// Then use it in your routes:
router.put("/", ..., validateDeviceUpdateFields, ...);
router.put("/soft", ..., validateDeviceUpdateFields, ...);

This refactoring would make the code more DRY (Don't Repeat Yourself) and easier to maintain.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 1736-1736: src/device-registry/routes/v2/devices.js#L1736
Added line #L1736 was not covered by tests

@Baalmart Baalmart merged commit fd2277c into staging Oct 21, 2024
50 checks passed
@Baalmart Baalmart deleted the hf-devices-validation branch October 21, 2024 21:08
@Baalmart Baalmart mentioned this pull request Oct 21, 2024
1 task
@coderabbitai coderabbitai bot mentioned this pull request Oct 21, 2024
10 tasks
@coderabbitai coderabbitai bot mentioned this pull request Nov 28, 2024
10 tasks
@coderabbitai coderabbitai bot mentioned this pull request Jan 29, 2025
10 tasks
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