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

just a small hotfix for device updates #3943

Merged
merged 1 commit into from
Nov 28, 2024
Merged

just a small hotfix for device updates #3943

merged 1 commit into from
Nov 28, 2024

Conversation

Baalmart
Copy link
Contributor

@Baalmart Baalmart commented Nov 28, 2024

Description

just a small hotfix for device updates

Changes Made

  • just a small hotfix for device updates

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:
    • Soft Update Device

API Documentation Updated?

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

Additional Notes

just a small hotfix for device updates

Summary by CodeRabbit

  • New Features

    • Enhanced device management with improved handling for new document creation and updates, including default settings and sanitization.
    • Introduced error handling to ensure robust operation during device updates.
  • Bug Fixes

    • Resolved issues related to serial number and device number adjustments during updates.

Copy link
Contributor

coderabbitai bot commented Nov 28, 2024

📝 Walkthrough

Walkthrough

The pull request introduces significant changes to the deviceSchema in Device.js, primarily by replacing the existing post("save") hook with a new pre hook applicable to multiple operations, including update and save. This new hook restructures the logic for handling both new document creation and updates, ensuring proper default values, sanitization, and error handling. It enhances the control flow by managing various conditions and operations consistently across different document states.

Changes

File Path Change Summary
src/device-registry/models/Device.js - Replaced post("save") with a pre hook for multiple operations.
- Implemented logic for new document creation and updates, including default value setting and sanitization.
- Enhanced error handling with try-catch blocks.
- Updated method signature for the pre-hook to handle various operations.

Possibly related PRs

🌟 In the realm of code, where devices play,
A new hook emerges, brightening the way.
With defaults and checks, it dances with grace,
Ensuring our data finds its rightful place.
So here's to the changes, both clever and bold,
In the world of Device, new stories unfold! 🎉


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 Nov 28, 2024

Codecov Report

Attention: Patch coverage is 1.51515% with 65 lines in your changes missing coverage. Please review.

Project coverage is 11.73%. Comparing base (ca75dd7) to head (c8e68e3).

Files with missing lines Patch % Lines
src/device-registry/models/Device.js 1.51% 65 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           staging    #3943      +/-   ##
===========================================
- Coverage    11.74%   11.73%   -0.02%     
===========================================
  Files          114      114              
  Lines        15317    15318       +1     
  Branches       318      318              
===========================================
- Hits          1799     1797       -2     
- Misses       13518    13521       +3     
Files with missing lines Coverage Δ
src/device-registry/models/Device.js 13.82% <1.51%> (-1.15%) ⬇️

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

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

292-298: Avoid code duplication by extracting sanitizeName function

The sanitizeName function is defined twice within the pre hook. To improve maintainability and readability, consider defining it once outside the conditional blocks to avoid duplication.

Apply this diff to extract the function:

+  // Define sanitizeName function outside of conditional blocks
+  const sanitizeName = (name) => {
+    return name
+      .replace(/[^a-zA-Z0-9]/g, "_")
+      .slice(0, 41)
+      .trim()
+      .toLowerCase();
+  };

   if (isNew) {
-    // Sanitize name
-    const sanitizeName = (name) => {
-      return name
-        .replace(/[^a-zA-Z0-9]/g, "_")
-        .slice(0, 41)
-        .trim()
-        .toLowerCase();
-    };

     if (this.name) {
       this.name = sanitizeName(this.name);
     } else if (this.long_name) {
       this.name = sanitizeName(this.long_name);
     }
     // Other code...
   }

   // Later in the code
   if (updateData.name) {
-    const sanitizeName = (name) => {
-      return name
-        .replace(/[^a-zA-Z0-9]/g, "_")
-        .slice(0, 41)
-        .trim()
-        .toLowerCase();
-    };
     updateData.name = sanitizeName(updateData.name);
   }

Also applies to: 356-361

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 292-293: src/device-registry/models/Device.js#L292-L293
Added lines #L292 - L293 were not covered by tests

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ca75dd7 and c8e68e3.

📒 Files selected for processing (1)
  • src/device-registry/models/Device.js (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/device-registry/models/Device.js

[error] 379-379: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 384-384: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 389-389: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🪛 GitHub Check: codecov/patch
src/device-registry/models/Device.js

[warning] 250-250: src/device-registry/models/Device.js#L250
Added line #L250 was not covered by tests


[warning] 252-253: src/device-registry/models/Device.js#L252-L253
Added lines #L252 - L253 were not covered by tests


[warning] 255-255: src/device-registry/models/Device.js#L255
Added line #L255 was not covered by tests


[warning] 257-258: src/device-registry/models/Device.js#L257-L258
Added lines #L257 - L258 were not covered by tests


[warning] 262-265: src/device-registry/models/Device.js#L262-L265
Added lines #L262 - L265 were not covered by tests


[warning] 274-275: src/device-registry/models/Device.js#L274-L275
Added lines #L274 - L275 were not covered by tests


[warning] 279-282: src/device-registry/models/Device.js#L279-L282
Added lines #L279 - L282 were not covered by tests


[warning] 292-293: src/device-registry/models/Device.js#L292-L293
Added lines #L292 - L293 were not covered by tests


[warning] 300-303: src/device-registry/models/Device.js#L300-L303
Added lines #L300 - L303 were not covered by tests


[warning] 307-308: src/device-registry/models/Device.js#L307-L308
Added lines #L307 - L308 were not covered by tests


[warning] 312-314: src/device-registry/models/Device.js#L312-L314
Added lines #L312 - L314 were not covered by tests


[warning] 318-320: src/device-registry/models/Device.js#L318-L320
Added lines #L318 - L320 were not covered by tests


[warning] 322-323: src/device-registry/models/Device.js#L322-L323
Added lines #L322 - L323 were not covered by tests


[warning] 325-326: src/device-registry/models/Device.js#L325-L326
Added lines #L325 - L326 were not covered by tests


[warning] 330-331: src/device-registry/models/Device.js#L330-L331
Added lines #L330 - L331 were not covered by tests


[warning] 334-335: src/device-registry/models/Device.js#L334-L335
Added lines #L334 - L335 were not covered by tests


[warning] 345-349: src/device-registry/models/Device.js#L345-L349
Added lines #L345 - L349 were not covered by tests


[warning] 354-356: src/device-registry/models/Device.js#L354-L356
Added lines #L354 - L356 were not covered by tests


[warning] 362-362: src/device-registry/models/Device.js#L362
Added line #L362 was not covered by tests


[warning] 366-367: src/device-registry/models/Device.js#L366-L367
Added lines #L366 - L367 were not covered by tests


[warning] 371-371: src/device-registry/models/Device.js#L371
Added line #L371 was not covered by tests


[warning] 375-375: src/device-registry/models/Device.js#L375
Added line #L375 was not covered by tests


[warning] 377-379: src/device-registry/models/Device.js#L377-L379
Added lines #L377 - L379 were not covered by tests


[warning] 382-384: src/device-registry/models/Device.js#L382-L384
Added lines #L382 - L384 were not covered by tests


[warning] 387-389: src/device-registry/models/Device.js#L387-L389
Added lines #L387 - L389 were not covered by tests


[warning] 393-394: src/device-registry/models/Device.js#L393-L394
Added lines #L393 - L394 were not covered by tests


[warning] 397-397: src/device-registry/models/Device.js#L397
Added line #L397 was not covered by tests


[warning] 399-399: src/device-registry/models/Device.js#L399
Added line #L399 was not covered by tests


[warning] 596-596: src/device-registry/models/Device.js#L596
Added line #L596 was not covered by tests

Comment on lines +250 to +254
try {
// Determine if this is a new document or an update
const isNew = this.isNew;
const updateData = this.getUpdate ? this.getUpdate() : this;

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 correct use of this.isNew and this.getUpdate() in pre-hooks

In Mongoose query middleware (e.g., pre-hooks for 'update' operations), this refers to the query object, and properties like isNew are not available. Similarly, in document middleware, methods like getUpdate() are not present. Combining both query and document middleware in a single hook may lead to unexpected behavior. Consider separating the middleware for query and document operations or adjusting the logic to handle each case appropriately.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 250-250: src/device-registry/models/Device.js#L250
Added line #L250 was not covered by tests


[warning] 252-253: src/device-registry/models/Device.js#L252-L253
Added lines #L252 - L253 were not covered by tests

Comment on lines +240 to +398
}
}

deviceSchema.pre(
["update", "findByIdAndUpdate", "updateMany", "updateOne"],
function(next) {
// Enable validation on update
this.setOptions({ runValidators: true });

const updateData = this.getUpdate(); // Get the data being updated

// Handling the network condition
if (updateData.network === "airqo") {
if (updateData.device_number) {
updateData.serial_number = String(updateData.device_number);
} else if (updateData.serial_number) {
updateData.device_number = Number(updateData.serial_number);
// Sanitize name if modified
if (updateData.name) {
const sanitizeName = (name) => {
return name
.replace(/[^a-zA-Z0-9]/g, "_")
.slice(0, 41)
.trim()
.toLowerCase();
};
updateData.name = sanitizeName(updateData.name);
}
}

// Sanitize name if modified
if (updateData.name) {
const sanitizeName = (name) => {
return name
.replace(/[^a-zA-Z0-9]/g, "_")
.slice(0, 41)
.trim()
.toLowerCase();
};
updateData.name = sanitizeName(updateData.name);
}
// Generate access code if present in update
if (updateData.access_code) {
const access_code = accessCodeGenerator.generate({
length: 16,
excludeSimilarCharacters: true,
});
updateData.access_code = access_code.toUpperCase();
}

// Generate access code if present in update
if (updateData.access_code) {
const access_code = accessCodeGenerator.generate({
length: 16,
excludeSimilarCharacters: true,
});
updateData.access_code = access_code.toUpperCase();
}
// Handle $addToSet for device_codes, previous_sites, and pictures
const addToSetUpdates = {};

// Handle $addToSet for device_codes, previous_sites, and pictures
const addToSetUpdates = {};
if (updateData.device_codes) {
addToSetUpdates.device_codes = { $each: updateData.device_codes };
delete updateData.device_codes; // Remove from main update object
}

if (updateData.device_codes) {
addToSetUpdates.device_codes = { $each: updateData.device_codes };
delete updateData.device_codes; // Remove from main update object
}
if (updateData.previous_sites) {
addToSetUpdates.previous_sites = { $each: updateData.previous_sites };
delete updateData.previous_sites; // Remove from main update object
}

if (updateData.previous_sites) {
addToSetUpdates.previous_sites = { $each: updateData.previous_sites };
delete updateData.previous_sites; // Remove from main update object
}
if (updateData.pictures) {
addToSetUpdates.pictures = { $each: updateData.pictures };
delete updateData.pictures; // Remove from main update object
}

if (updateData.pictures) {
addToSetUpdates.pictures = { $each: updateData.pictures };
delete updateData.pictures; // Remove from main update object
}
// If there are any $addToSet updates, merge them into the main update object
if (Object.keys(addToSetUpdates).length > 0) {
updateData.$addToSet = addToSetUpdates;
}

// If there are any $addToSet updates, merge them into the main update object
if (Object.keys(addToSetUpdates).length > 0) {
updateData.$addToSet = addToSetUpdates;
next();
} catch (error) {
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

Add unit tests for new pre hook logic

The new pre hook introduces significant logic for handling document creation and updates. To ensure the code behaves as expected and to prevent future regressions, please add unit tests that cover the new scenarios and code paths.

Would you like assistance in creating test cases for this new functionality?

🧰 Tools
🪛 Biome (1.9.4)

[error] 379-379: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 384-384: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 389-389: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🪛 GitHub Check: codecov/patch

[warning] 250-250: src/device-registry/models/Device.js#L250
Added line #L250 was not covered by tests


[warning] 252-253: src/device-registry/models/Device.js#L252-L253
Added lines #L252 - L253 were not covered by tests


[warning] 255-255: src/device-registry/models/Device.js#L255
Added line #L255 was not covered by tests


[warning] 257-258: src/device-registry/models/Device.js#L257-L258
Added lines #L257 - L258 were not covered by tests


[warning] 262-265: src/device-registry/models/Device.js#L262-L265
Added lines #L262 - L265 were not covered by tests


[warning] 274-275: src/device-registry/models/Device.js#L274-L275
Added lines #L274 - L275 were not covered by tests


[warning] 279-282: src/device-registry/models/Device.js#L279-L282
Added lines #L279 - L282 were not covered by tests


[warning] 292-293: src/device-registry/models/Device.js#L292-L293
Added lines #L292 - L293 were not covered by tests


[warning] 300-303: src/device-registry/models/Device.js#L300-L303
Added lines #L300 - L303 were not covered by tests


[warning] 307-308: src/device-registry/models/Device.js#L307-L308
Added lines #L307 - L308 were not covered by tests


[warning] 312-314: src/device-registry/models/Device.js#L312-L314
Added lines #L312 - L314 were not covered by tests


[warning] 318-320: src/device-registry/models/Device.js#L318-L320
Added lines #L318 - L320 were not covered by tests


[warning] 322-323: src/device-registry/models/Device.js#L322-L323
Added lines #L322 - L323 were not covered by tests


[warning] 325-326: src/device-registry/models/Device.js#L325-L326
Added lines #L325 - L326 were not covered by tests


[warning] 330-331: src/device-registry/models/Device.js#L330-L331
Added lines #L330 - L331 were not covered by tests


[warning] 334-335: src/device-registry/models/Device.js#L334-L335
Added lines #L334 - L335 were not covered by tests


[warning] 345-349: src/device-registry/models/Device.js#L345-L349
Added lines #L345 - L349 were not covered by tests


[warning] 354-356: src/device-registry/models/Device.js#L354-L356
Added lines #L354 - L356 were not covered by tests


[warning] 362-362: src/device-registry/models/Device.js#L362
Added line #L362 was not covered by tests


[warning] 366-367: src/device-registry/models/Device.js#L366-L367
Added lines #L366 - L367 were not covered by tests


[warning] 371-371: src/device-registry/models/Device.js#L371
Added line #L371 was not covered by tests


[warning] 375-375: src/device-registry/models/Device.js#L375
Added line #L375 was not covered by tests


[warning] 377-379: src/device-registry/models/Device.js#L377-L379
Added lines #L377 - L379 were not covered by tests


[warning] 382-384: src/device-registry/models/Device.js#L382-L384
Added lines #L382 - L384 were not covered by tests


[warning] 387-389: src/device-registry/models/Device.js#L387-L389
Added lines #L387 - L389 were not covered by tests


[warning] 393-394: src/device-registry/models/Device.js#L393-L394
Added lines #L393 - L394 were not covered by tests


[warning] 397-397: src/device-registry/models/Device.js#L397
Added line #L397 was not covered by tests

@Baalmart Baalmart merged commit 46894f9 into staging Nov 28, 2024
50 of 52 checks passed
@Baalmart Baalmart deleted the hf-device-updates branch November 28, 2024 03:36
@Baalmart Baalmart mentioned this pull request Nov 28, 2024
1 task
@coderabbitai coderabbitai bot mentioned this pull request Dec 12, 2024
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